Merge remote-tracking branch 'origin/main' into feat/REQ-20260922-0004-paper-percapita

# Conflicts:
#	xiaoqu-agent-service/README.md
#	xiaoqu-agent-service/doc/agent-mcp-tools-reference.md
This commit is contained in:
qiudl
2026-09-22 11:30:56 +02:00
20 changed files with 1664 additions and 43 deletions
@@ -22,6 +22,8 @@ import java.util.Arrays;
* 双集群 ES 客户端:cloud=云集群、local=本地化集群(老系统 Dictionary.LocalEsDate 分界)。
* 低阶 RestClient 也注册为 bean(destroyMethod=close 随容器关闭);
* 高阶 ElasticsearchClient 包装同一 RestClient,关闭 client 即关闭底层连接。
* 注意:生产两个集群均为 ES 7.7.1,高阶客户端(7.17)的 vendor Content-Type 与
* X-Elastic-Product 校验与 7.7.1 不兼容(406),业务查询一律注入低阶 RestClient bean。
*/
@Configuration
public class EsClientConfig {
@@ -0,0 +1,45 @@
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.battery_fault_log)。 */
@Getter
@Setter
@ToString
@TableName("battery_fault_log")
public class BatteryFaultLog 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;
private Integer deviceType;
private Integer faultType;
private Integer faultState;
private Date faultStartTime;
private Date faultAddTime;
private Date faultRecoveryTime;
private String installPosition;
private Long districtId;
private String districtName;
private Long propertyId;
private String propertyName;
private Long agentId;
private String agentName;
private Integer peakValue;
private Integer standardValue;
}
@@ -0,0 +1,70 @@
package me.iiv.agent.es;
import java.util.List;
/**
* electricitymessage_yyyyMM(设备电量/信号/温度等消息)ES 查询网关。
* 只走本地 ES 集群(索引只建在本地集群),索引名由调用方按月构造传入,
* 本接口只做单次查询,便于单测 mock。
*/
public interface ElectricityMessageEsGateway {
/**
* 分页查询单台设备的电量/信号/温度/充电循环次数/电压/电流消息记录。
*
* @param index 月索引名,如 electricitymessage_202609(由调用方按 startTime 月份构造)
* @param snCode 设备 SN,match_phrase 精确短语匹配
* @param messageType 消息类型 0-5,null=不过滤(查全部类型)
* @param startTime createTime 下界(含),yyyy-MM-dd HH:mm:ss
* @param endTime createTime 上界(含),yyyy-MM-dd HH:mm:ss
* @param from from+size 分页起始偏移
* @param size 每页条数
* @return 命中总数(track_total_hits)与当页记录,按 createTime ASC
*/
Result search(String index, String snCode, Integer messageType,
String startTime, String endTime, int from, int size);
/** 单次查询结果。 */
class Result {
private final long total;
private final List<Record> records;
public Result(long total, List<Record> records) {
this.total = total;
this.records = records;
}
public long getTotal() {
return total;
}
public List<Record> getRecords() {
return records;
}
}
/** 单条消息记录(createTime 已统一为 yyyy-MM-dd HH:mm:ss 文本,未标注单位语义)。 */
class Record {
private final String createTime;
private final Integer messageType;
private final Integer value;
public Record(String createTime, Integer messageType, Integer value) {
this.createTime = createTime;
this.messageType = messageType;
this.value = value;
}
public String getCreateTime() {
return createTime;
}
public Integer getMessageType() {
return messageType;
}
public Integer getValue() {
return value;
}
}
}
@@ -0,0 +1,142 @@
package me.iiv.agent.es;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
/**
* electricitymessage_yyyyMM ES 查询实现。
* 降级原因:生产 ES 集群为 7.7.1,elasticsearch-java 7.17 高阶客户端(ElasticsearchClient)
* 请求自带 vendor Content-Type(application/vnd.elasticsearch+json; compatible-with=7)被
* 7.7.1 以 406 Not Acceptable 拒绝,且 7.17 客户端校验响应 X-Elastic-Product 头(7.14 才引入),
* 7.7.1 没有,二次兼容也过不了;故改用低阶 RestClient(只发普通 application/json、无产品头校验)。
* 只注入 esLocalRestClient(索引只在本地集群,不走 esCloud)。
* 查询口径对齐老 BatteryAnalyseController.batteryAnalyseList 但修掉其坑:
* snCode 用 match_phrase(老代码 matchQuery 经 standard analyzer 会把 AB-123 切成 ab/123 误配)、
* messageType 不传不加 term(老代码默认值 0 会把"不传"歧义成"电量")、createTime 闭区间 range、
* createTime ASC 排序、from+size 分页(老代码 scroll 拉全量后内存抽样)。
* ES 异常不静默,抛 IllegalStateException(与老系统 catch 吞异常返回空不同,见设计文档)。
*/
@Component
public class ElectricityMessageEsGatewayImpl implements ElectricityMessageEsGateway {
private static final ZoneId BUSINESS_ZONE = ZoneId.of("Asia/Shanghai");
private static final DateTimeFormatter TIME_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(BUSINESS_ZONE);
private final RestClient localRestClient;
private final ObjectMapper mapper = new ObjectMapper();
public ElectricityMessageEsGatewayImpl(@Qualifier("esLocalRestClient") RestClient localRestClient) {
this.localRestClient = localRestClient;
}
@Override
public Result search(String index, String snCode, Integer messageType,
String startTime, String endTime, int from, int size) {
ArrayNode filters = mapper.createArrayNode();
// 老代码 snCode 字符串走 matchQuery(BaseSearchSupportImpl2 type=0 非数值分支),
// standard analyzer 会把 AB-123 切成 ab/123 造成误配;改用 match_phrase 精确短语
filters.addObject().putObject("match_phrase").putObject("snCode").put("query", snCode);
if (messageType != null) {
filters.addObject().putObject("term").putObject("messageType").put("value", messageType);
}
// createTime 在索引里是 date 类型(format strict_date_optional_time||epoch_millis),
// 老系统经 DateUtils.parseDate 转 Date 后由 transport 序列化为 epoch 毫秒——
// 直接把 yyyy-MM-dd HH:mm:ss 字符串发过去会被 400 拒绝(format 不接受空格分隔)
ObjectNode range = filters.addObject().putObject("range").putObject("createTime");
range.put("gte", toEpochMillis(startTime)).put("lte", toEpochMillis(endTime));
ObjectNode body = mapper.createObjectNode();
body.put("from", from).put("size", size);
body.put("track_total_hits", true);
ObjectNode bool = body.putObject("query").putObject("bool");
bool.set("filter", filters);
body.putArray("sort").addObject().putObject("createTime").put("order", "asc");
try {
Request req = new Request("POST", "/" + index + "/_search");
// setJsonEntity 自动带 Content-Type: application/json(无 vendor 头)
req.setJsonEntity(mapper.writeValueAsString(body));
Response resp = localRestClient.performRequest(req);
JsonNode root = mapper.readTree(resp.getEntity().getContent());
List<Record> records = new ArrayList<>();
for (JsonNode hit : root.at("/hits/hits")) {
JsonNode source = hit.get("_source");
if (source == null) {
continue;
}
records.add(new Record(createTimeText(source.get("createTime")),
integerValue(source.get("messageType")),
integerValue(source.get("value"))));
}
return new Result(root.at("/hits/total/value").asLong(), records);
} catch (IOException | RuntimeException e) {
throw new IllegalStateException("ES 查询电量消息记录失败: " + e.getMessage(), e);
}
}
private long toEpochMillis(String timeText) {
return TIME_FORMATTER.parse(timeText, Instant::from).toEpochMilli();
}
/**
* createTime 在 _source 里是 ISO 文本(如 2026-09-21T10:00:00.000+08:00)或 epoch 毫秒数;
* 两种形态都归一为 Asia/Shanghai yyyy-MM-dd HH:mm:ss 文本输出(对齐老系统 Date 格式化口径)。
*/
private static String createTimeText(JsonNode value) {
if (value == null || value.isNull()) {
return null;
}
if (value.isNumber()) {
return TIME_FORMATTER.format(Instant.ofEpochMilli(value.longValue()));
}
if (value.isTextual()) {
String text = value.asText();
if (text.indexOf('T') >= 0) {
try {
return TIME_FORMATTER.format(OffsetDateTime.parse(text));
} catch (DateTimeParseException e) {
return text;
}
}
return text;
}
return null;
}
/**
* value 在 _source 里可能是数字也可能是字符串(索引实际为 "28"/"100" 文本),
* 统一解析为 Integer;非数值文本返回 null。
*/
private static Integer integerValue(JsonNode value) {
if (value == null || value.isNull()) {
return null;
}
if (value.isNumber()) {
return value.intValue();
}
if (value.isTextual()) {
try {
return Integer.valueOf(value.asText().trim());
} catch (NumberFormatException e) {
return null;
}
}
return null;
}
}
@@ -1,19 +1,24 @@
package me.iiv.agent.es;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.json.JsonData;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* paperuselog ES 查询实现(elasticsearch-java 7.17 强类型 API)。
* paperuselog ES 查询实现。
* 降级原因:生产 ES 集群为 7.7.1,elasticsearch-java 7.17 高阶客户端(ElasticsearchClient)
* 请求自带 vendor Content-Type(application/vnd.elasticsearch+json; compatible-with=7)被
* 7.7.1 以 406 Not Acceptable 拒绝,且 7.17 客户端校验响应 X-Elastic-Product 头(7.14 才引入),
* 7.7.1 没有,二次兼容也过不了;故改用低阶 RestClient(只发普通 application/json、无产品头校验)。
* 查询口径对齐老 MonthlyStatisticsController.getMonthlyStatisticsMap:
* term districtId/gender、range createTime [gte,lte](含边界)、deviceType 用 match(老代码字符串参数走 match),
* positionMode 厕位=positionsId>0、厕墙=positionsId=0。
@@ -25,31 +30,40 @@ public class PaperUseLogEsGatewayImpl implements PaperUseLogEsGateway {
/** rfid terms 聚合去重上限,超出部分不计入 */
private static final int RFID_TERMS_SIZE = 10000;
private final ElasticsearchClient cloudClient;
private final ElasticsearchClient localClient;
private final RestClient cloudRestClient;
private final RestClient localRestClient;
private final ObjectMapper mapper = new ObjectMapper();
public PaperUseLogEsGatewayImpl(@Qualifier("esCloudClient") ElasticsearchClient cloudClient,
@Qualifier("esLocalClient") ElasticsearchClient localClient) {
this.cloudClient = cloudClient;
this.localClient = localClient;
public PaperUseLogEsGatewayImpl(@Qualifier("esCloudRestClient") RestClient cloudRestClient,
@Qualifier("esLocalRestClient") RestClient localRestClient) {
this.cloudRestClient = cloudRestClient;
this.localRestClient = localRestClient;
}
@Override
public long distinctRfidCount(String index, boolean localCluster, Long districtId, Integer gender,
Long fromMillis, Long toMillis, Integer deviceType, String positionMode) {
List<Query> filters = baseFilters(districtId, gender, fromMillis, toMillis, deviceType, positionMode);
ArrayNode filters = baseFilters(districtId, gender, fromMillis, toMillis, deviceType, positionMode);
// 上纸(2)+撤纸(4) 合并后 rfid 去重(老 :302-342)
filters.add(Query.of(q -> q.terms(t -> t.field("state")
.terms(tt -> tt.value(List.of(FieldValue.of(2), FieldValue.of(4)))))));
// 正确结构是 {"terms":{"state":[2,4]}};写成 {"terms":{"state":{"terms":[...]}}} 会被 ES 以 400 拒绝(2026-09-22 生产实测)
ArrayNode stateTerms = filters.addObject().putObject("terms").putArray("state");
stateTerms.add(2).add(4);
try {
return client(localCluster).search(s -> s
.index(index)
.size(0)
.trackTotalHits(t -> t.enabled(true))
.query(q -> q.bool(b -> b.filter(filters)))
.aggregations("rfids", a -> a.terms(t -> t.field("rfid").size(RFID_TERMS_SIZE))),
Void.class)
.aggregations().get("rfids").sterms().buckets().array().size();
ObjectNode body = mapper.createObjectNode();
body.put("size", 0);
body.put("track_total_hits", false);
ObjectNode bool = body.putObject("query").putObject("bool");
bool.set("filter", filters);
// rfid 是 text 类型(mapping 含 ignore_above=256 的 keyword 子字段),terms 聚合必须用 rfid.keyword,
// 直接聚合 text 字段报 "Text fields are not optimised for ... aggregations"(400,生产实测)
body.putObject("aggs").putObject("rfids").putObject("terms")
.put("field", "rfid.keyword").put("size", RFID_TERMS_SIZE);
Request req = new Request("POST", "/" + index + "/_search");
req.setJsonEntity(mapper.writeValueAsString(body));
Response resp = client(localCluster).performRequest(req);
JsonNode root = mapper.readTree(resp.getEntity().getContent());
return root.at("/aggregations/rfids/buckets").size();
} catch (IOException | RuntimeException e) {
throw new IllegalStateException("ES 查询换纸 rfid 去重失败: " + e.getMessage(), e);
}
@@ -58,40 +72,47 @@ public class PaperUseLogEsGatewayImpl implements PaperUseLogEsGateway {
@Override
public long countState2(String index, boolean localCluster, Long districtId, Integer gender,
Long fromMillis, Long toMillis, Integer deviceType, String positionMode) {
List<Query> filters = baseFilters(districtId, gender, fromMillis, toMillis, deviceType, positionMode);
filters.add(Query.of(q -> q.term(t -> t.field("state").value(FieldValue.of(2)))));
ArrayNode filters = baseFilters(districtId, gender, fromMillis, toMillis, deviceType, positionMode);
filters.addObject().putObject("term").putObject("state").put("value", 2);
try {
return client(localCluster).count(c -> c.index(index)
.query(q -> q.bool(b -> b.filter(filters)))).count();
ObjectNode body = mapper.createObjectNode();
ObjectNode bool = body.putObject("query").putObject("bool");
bool.set("filter", filters);
Request req = new Request("POST", "/" + index + "/_count");
req.setJsonEntity(mapper.writeValueAsString(body));
Response resp = client(localCluster).performRequest(req);
JsonNode root = mapper.readTree(resp.getEntity().getContent());
return root.get("count").asLong();
} catch (IOException | RuntimeException e) {
throw new IllegalStateException("ES 查询换纸上纸记录数失败: " + e.getMessage(), e);
}
}
private List<Query> baseFilters(Long districtId, Integer gender, Long fromMillis, Long toMillis,
Integer deviceType, String positionMode) {
List<Query> filters = new ArrayList<>();
filters.add(Query.of(q -> q.term(t -> t.field("districtId").value(FieldValue.of(districtId)))));
filters.add(Query.of(q -> q.term(t -> t.field("gender").value(FieldValue.of(gender)))));
private ArrayNode baseFilters(Long districtId, Integer gender, Long fromMillis, Long toMillis,
Integer deviceType, String positionMode) {
ArrayNode filters = mapper.createArrayNode();
filters.addObject().putObject("term").putObject("districtId").put("value", districtId);
filters.addObject().putObject("term").putObject("gender").put("value", gender);
// createTime 为 epoch 毫秒;含边界(老 rangeQuery from/to 均 inclusive)
filters.add(Query.of(q -> q.range(r -> r.field("createTime")
.gte(JsonData.of(fromMillis)).lte(JsonData.of(toMillis)))));
ObjectNode range = filters.addObject().putObject("range").putObject("createTime");
range.put("gte", fromMillis).put("lte", toMillis);
if (deviceType != null) {
// 老代码 deviceType 为字符串参数走 matchQuery(BaseSearchSupportImpl2 type=0 非数值分支)
filters.add(Query.of(q -> q.match(m -> m.field("deviceType")
.query(FieldValue.of(String.valueOf(deviceType))))));
filters.addObject().putObject("match").putObject("deviceType")
.put("query", String.valueOf(deviceType));
}
if (StringUtils.hasText(positionMode)) {
if ("position".equals(positionMode)) {
filters.add(Query.of(q -> q.range(r -> r.field("positionsId").gt(JsonData.of(0)))));
filters.addObject().putObject("range").putObject("positionsId").put("gt", 0);
} else {
filters.add(Query.of(q -> q.term(t -> t.field("positionsId").value(FieldValue.of(0)))));
filters.addObject().putObject("term").putObject("positionsId").put("value", 0);
}
}
return filters;
}
private ElasticsearchClient client(boolean localCluster) {
return localCluster ? localClient : cloudClient;
private RestClient client(boolean localCluster) {
return localCluster ? localRestClient : cloudRestClient;
}
}
@@ -0,0 +1,7 @@
package me.iiv.agent.mapper.m0;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import me.iiv.agent.entity.m0.BatteryFaultLog;
public interface BatteryFaultLogMapper extends BaseMapper<BatteryFaultLog> {
}
@@ -0,0 +1,172 @@
package me.iiv.agent.mcp.tool;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.iiv.agent.entity.m0.BatteryFaultLog;
import me.iiv.agent.entity.m0.User;
import me.iiv.agent.mapper.m0.BatteryFaultLogMapper;
import me.iiv.agent.mcp.ToolObject;
import me.iiv.agent.mcp.XqTool;
import me.iiv.agent.permission.PermissionService;
import me.iiv.agent.security.AuthContextHolder;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/** 电池故障列表查询工具,对应老系统 /batteryFault/batteryFaultLogList。 */
@Component
public class BatteryFaultTools implements ToolObject {
private static final int DEFAULT_ROWS = 20;
private static final int MAX_ROWS = 100;
private static final ZoneId BUSINESS_ZONE = ZoneId.of("Asia/Shanghai");
private static final DateTimeFormatter TIME_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(BUSINESS_ZONE);
final BatteryFaultLogMapper mapper;
final PermissionService permissionService;
public BatteryFaultTools(BatteryFaultLogMapper mapper, PermissionService permissionService) {
this.mapper = mapper;
this.permissionService = permissionService;
}
@XqTool(category = "hardware", kind = "read")
@Tool(name = "battery.fault.list.query", description = "分页查询当前身份可见的电池故障记录,对应老系统"
+ " /batteryFault/batteryFaultLogList。支持站点、物业、代理商、设备 SN、设备类型、故障类型、"
+ "恢复状态及故障日期范围筛选;page 默认 1,rows 默认 20、上限 100;"
+ "固定按 fault_start_time DESC、id DESC 排序。")
public Map<String, Object> batteryFaultListQuery(
@ToolParam(required = false, description = "站点 id,正整数") Long districtId,
@ToolParam(required = false, description = "物业 id,正整数") Long propertyId,
@ToolParam(required = false, description = "代理商 id,正整数") Long agentId,
@ToolParam(required = false, description = "设备 SN,模糊匹配") String snCode,
@ToolParam(required = false, description = "设备类型:0=厕纸机/出纸机,1=擦手纸机") Integer deviceType,
@ToolParam(required = false, description = "故障类型:0=温度异常,1=电压异常,2=电流异常,3=充电次数异常") Integer faultType,
@ToolParam(required = false, description = "故障状态:0=未恢复,1=已恢复") Integer faultState,
@ToolParam(required = false, description = "故障日期起始,yyyy-MM-dd,包含当天") String faultDateFrom,
@ToolParam(required = false, description = "故障日期结束,yyyy-MM-dd,包含当天") String faultDateTo,
@ToolParam(required = false, description = "页码,从 1 开始,默认 1") Integer page,
@ToolParam(required = false, description = "每页条数,默认 20,上限 100") Integer rows) {
validatePositive(districtId, "districtId");
validatePositive(propertyId, "propertyId");
validatePositive(agentId, "agentId");
validateEnum(deviceType, "deviceType", 0, 1);
validateEnum(faultType, "faultType", 0, 1, 2, 3);
validateEnum(faultState, "faultState", 0, 1);
LocalDate from = parseDate(faultDateFrom, "faultDateFrom");
LocalDate to = parseDate(faultDateTo, "faultDateTo");
if (from != null && to != null && from.isAfter(to)) {
throw new IllegalArgumentException("faultDateFrom 不能晚于 faultDateTo");
}
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<BatteryFaultLog> wrapper = new LambdaQueryWrapper<BatteryFaultLog>()
.eq(BatteryFaultLog::getSoftDelete, 0)
.eq(districtId != null, BatteryFaultLog::getDistrictId, districtId)
.eq(propertyId != null, BatteryFaultLog::getPropertyId, propertyId)
.eq(agentId != null, BatteryFaultLog::getAgentId, agentId)
.eq(deviceType != null, BatteryFaultLog::getDeviceType, deviceType)
.eq(faultType != null, BatteryFaultLog::getFaultType, faultType)
.eq(faultState != null, BatteryFaultLog::getFaultState, faultState);
if (StringUtils.hasText(snCode)) {
wrapper.like(BatteryFaultLog::getSnCode, snCode.trim());
}
if (from != null) {
wrapper.ge(BatteryFaultLog::getFaultStartTime,
Date.from(from.atStartOfDay(BUSINESS_ZONE).toInstant()));
}
if (to != null) {
wrapper.lt(BatteryFaultLog::getFaultStartTime,
Date.from(to.plusDays(1).atStartOfDay(BUSINESS_ZONE).toInstant()));
}
User user = AuthContextHolder.get().getUser();
permissionService.applyBatteryFaultLogRowFilter(wrapper, user);
Long total = mapper.selectCount(wrapper);
wrapper.orderByDesc(BatteryFaultLog::getFaultStartTime)
.orderByDesc(BatteryFaultLog::getId)
.last("LIMIT " + (long) (pageNo - 1) * pageSize + "," + pageSize);
List<Map<String, Object>> records = mapper.selectList(wrapper).stream()
.map(this::record).collect(Collectors.toList());
Map<String, Object> result = new LinkedHashMap<>();
result.put("total", total);
result.put("page", pageNo);
result.put("rows", pageSize);
if (truncated) {
result.put("notice", "rows 超过上限 100,已截断为 100");
}
result.put("records", records);
return result;
}
private Map<String, Object> record(BatteryFaultLog log) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("id", log.getId());
row.put("snCode", log.getSnCode());
row.put("deviceType", log.getDeviceType());
row.put("deviceTypeText", text(log.getDeviceType(), "厕纸机", "擦手纸机"));
row.put("faultType", log.getFaultType());
row.put("faultTypeText", text(log.getFaultType(), "温度异常", "电压异常", "电流异常", "充电次数异常"));
row.put("faultState", log.getFaultState());
row.put("faultStateText", text(log.getFaultState(), "未恢复", "已恢复"));
row.put("peakValue", log.getPeakValue());
row.put("standardValue", log.getStandardValue());
row.put("faultStartTime", format(log.getFaultStartTime()));
row.put("faultAddTime", format(log.getFaultAddTime()));
row.put("faultRecoveryTime", format(log.getFaultRecoveryTime()));
row.put("installPosition", log.getInstallPosition());
row.put("agentId", log.getAgentId());
row.put("agentName", log.getAgentName());
row.put("propertyId", log.getPropertyId());
row.put("propertyName", log.getPropertyName());
row.put("districtId", log.getDistrictId());
row.put("districtName", log.getDistrictName());
return row;
}
private static LocalDate parseDate(String value, String name) {
if (!StringUtils.hasText(value)) {
return null;
}
try {
return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE);
} catch (DateTimeParseException ex) {
throw new IllegalArgumentException(name + " 必须为 yyyy-MM-dd 格式");
}
}
private static String format(Date value) {
return value == null ? null : TIME_FORMATTER.format(value.toInstant());
}
private static String text(Integer value, String... labels) {
return value != null && value >= 0 && value < labels.length ? labels[value] : null;
}
private static void validatePositive(Long value, String name) {
if (value != null && value <= 0) {
throw new IllegalArgumentException(name + " 必须为正整数");
}
}
private static void validateEnum(Integer value, String name, Integer... allowed) {
if (value != null && !Arrays.asList(allowed).contains(value)) {
throw new IllegalArgumentException(name + " 不在允许范围内");
}
}
}
@@ -0,0 +1,150 @@
package me.iiv.agent.mcp.tool;
import me.iiv.agent.es.ElectricityMessageEsGateway;
import me.iiv.agent.mcp.ToolObject;
import me.iiv.agent.mcp.XqTool;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 设备电量/信号/温度等消息记录查询工具(ES electricitymessage_yyyyMM 月索引),
* 对应老系统 /batteryAnalyse/batteryAnalyseList 的数据查询语义但修掉其坑。
* 按用户拍板:不做任何权限校验(对齐老系统)、只走 esLocal 本地集群、全量分页返回(不做抽样)。
*/
@Component
public class ElectricityMessageTools implements ToolObject {
private static final int DEFAULT_ROWS = 500;
private static final int MAX_ROWS = 1000;
/** ES from+size 深分页上限 max_result_window */
private static final int MAX_RESULT_WINDOW = 10000;
private static final String INDEX_PREFIX = "electricitymessage_";
private static final DateTimeFormatter STRICT_TIME = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM-dd HH:mm:ss").toFormatter().withResolverStyle(ResolverStyle.STRICT);
private static final DateTimeFormatter INDEX_MONTH = DateTimeFormatter.ofPattern("yyyyMM");
final ElectricityMessageEsGateway gateway;
public ElectricityMessageTools(ElectricityMessageEsGateway gateway) {
this.gateway = gateway;
}
@XqTool(category = "hardware", kind = "read")
@Tool(name = "hardware.electricity.message.list.query", description = "分页查询设备电量/信号/温度/充电循环次数/电压/电流消息记录"
+ "(ES electricitymessage_yyyyMM 月索引,只走本地集群,无权限过滤,对齐老系统"
+ " /batteryAnalyse/batteryAnalyseList)。snCode 必填;startTime/endTime 必填且必须为同一天"
+ "(只支持单日查询,跨天直接拒绝);messageType 可选,0=电量、1=信号、2=温度、3=充电循环次数、"
+ "4=电压、5=电流,不传=查全部类型;按 createTime ASC 排序,page 默认 1、rows 默认 500、上限 1000。")
public Map<String, Object> hardwareElectricityMessageListQuery(
@ToolParam(description = "设备 SN,必填,非空,match_phrase 精确短语匹配") String snCode,
@ToolParam(description = "开始时间,yyyy-MM-dd HH:mm:ss,必填,与 endTime 必须为同一天") String startTime,
@ToolParam(description = "结束时间,yyyy-MM-dd HH:mm:ss,必填,不早于 startTime") String endTime,
@ToolParam(required = false, description = "消息类型:0=电量,1=信号,2=温度,3=充电循环次数,4=电压,5=电流;不传=查全部类型") Integer messageType,
@ToolParam(required = false, description = "页码,从 1 开始,默认 1") Integer page,
@ToolParam(required = false, description = "每页条数,默认 500,上限 1000,超出截断为 1000") Integer rows) {
if (!StringUtils.hasText(snCode)) {
throw new IllegalArgumentException("snCode 必填,非空");
}
LocalDateTime start = parseTime(startTime, "startTime");
LocalDateTime end = parseTime(endTime, "endTime");
// 老系统只按开始时间的月份选索引,跨月范围静默丢数据;这里显式拒绝跨天查询
if (!start.toLocalDate().equals(end.toLocalDate())) {
throw new IllegalArgumentException("只支持单日查询:startTime 与 endTime 必须为同一天(yyyy-MM-dd)");
}
if (start.isAfter(end)) {
throw new IllegalArgumentException("startTime 不能晚于 endTime");
}
if (messageType != null && (messageType < 0 || messageType > 5)) {
throw new IllegalArgumentException("messageType 仅支持 0-5");
}
int pageNo = page == null || page < 1 ? 1 : page;
boolean truncatedRows = rows != null && rows > MAX_ROWS;
int pageSize = rows == null || rows < 1 ? DEFAULT_ROWS : Math.min(rows, MAX_ROWS);
long fromLong = (long) (pageNo - 1) * pageSize;
String windowNotice = null;
if (fromLong >= MAX_RESULT_WINDOW) {
// from+size 超出 ES max_result_window 会被 ES 拒绝,截断为窗口内最后可用的完整页
fromLong = MAX_RESULT_WINDOW - pageSize;
windowNotice = "查询起始位置超过 ES max_result_window(10000),已截断为第 "
+ (fromLong / pageSize + 1) + " 页起的最后可用窗口";
} else if (fromLong + pageSize > MAX_RESULT_WINDOW) {
windowNotice = "本页超出 ES max_result_window(10000),已截断为 " + (MAX_RESULT_WINDOW - fromLong) + " 条";
pageSize = MAX_RESULT_WINDOW - (int) fromLong;
}
String index = INDEX_PREFIX + INDEX_MONTH.format(start);
ElectricityMessageEsGateway.Result search = gateway.search(index, snCode.trim(), messageType,
startTime.trim(), endTime.trim(), (int) fromLong, pageSize);
List<Map<String, Object>> records = search.getRecords().stream()
.map(this::record)
.collect(Collectors.toList());
Map<String, Object> result = new LinkedHashMap<>();
result.put("snCode", snCode.trim());
result.put("index", index);
result.put("total", search.getTotal());
result.put("page", pageNo);
result.put("rows", pageSize);
String notice = notice(truncatedRows, windowNotice);
if (notice != null) {
result.put("notice", notice);
}
result.put("records", records);
return result;
}
private Map<String, Object> record(ElectricityMessageEsGateway.Record message) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("createTime", message.getCreateTime());
row.put("messageType", message.getMessageType());
row.put("messageTypeText", messageTypeText(message.getMessageType()));
row.put("value", message.getValue());
return row;
}
private static String notice(boolean truncatedRows, String windowNotice) {
StringBuilder builder = new StringBuilder();
if (truncatedRows) {
builder.append("rows 超过上限 1000,已截断为 1000");
}
if (windowNotice != null) {
if (builder.length() > 0) {
builder.append(";");
}
builder.append(windowNotice);
}
return builder.length() == 0 ? null : builder.toString();
}
private static String messageTypeText(Integer messageType) {
if (messageType == null || messageType < 0 || messageType > 5) {
return null;
}
String[] labels = {"电量", "信号", "温度", "充电循环次数", "电压", "电流"};
return labels[messageType];
}
private static LocalDateTime parseTime(String value, String name) {
if (!StringUtils.hasText(value)) {
throw new IllegalArgumentException(name + " 必填,格式 yyyy-MM-dd HH:mm:ss");
}
try {
return LocalDateTime.parse(value.trim(), STRICT_TIME);
} catch (DateTimeParseException ex) {
throw new IllegalArgumentException(name + " 格式非法,要求 yyyy-MM-dd HH:mm:ss: " + value);
}
}
}
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.BatteryFaultLog;
import me.iiv.agent.entity.m0.DistrictDistrictStrategy;
import me.iiv.agent.entity.m0.HardwareView;
import me.iiv.agent.entity.m0.Properyt;
@@ -833,6 +834,24 @@ public class PermissionService {
}
}
/** 电池故障日志行权限:与出纸机列表复用同一代理/物业可见范围。 */
public void applyBatteryFaultLogRowFilter(LambdaQueryWrapper<BatteryFaultLog> wrapper, User user) {
RowScope scope = resolveRowScope(user);
if (scope.headquarters) {
return;
}
if (scope.salesPropertyIds != null) {
wrapper.in(BatteryFaultLog::getPropertyId, scope.salesPropertyIds);
return;
}
if (!scope.managedPropertyIds.isEmpty()) {
wrapper.and(w -> w.in(BatteryFaultLog::getAgentId, scope.ids)
.or().in(BatteryFaultLog::getPropertyId, scope.managedPropertyIds));
} else {
wrapper.in(BatteryFaultLog::getAgentId, scope.ids);
}
}
/**
* 合同(m2 contract_new)行权限:与站点/出纸机同一 getByIsAgent 变体
* (propertyFlag=true),agent 维度落到 contract_agent_id(合同所属公司,