feat(mcp): 新增设备日均用纸统计工具 (REQ-20260922-0007)
This commit is contained in:
+19
@@ -0,0 +1,19 @@
|
||||
package me.iiv.agent.entity.m0;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** monthly_statistics 设备日均用纸数据库聚合结果。 */
|
||||
@Getter
|
||||
@Setter
|
||||
public class DeviceAverageAggregateRow {
|
||||
|
||||
private LocalDate statisticsDate;
|
||||
private String floor;
|
||||
private Integer genderCode;
|
||||
private BigDecimal paperLengthCm;
|
||||
private Long recordCount;
|
||||
}
|
||||
+17
@@ -1,7 +1,24 @@
|
||||
package me.iiv.agent.mapper.m0;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import me.iiv.agent.entity.m0.DeviceAverageAggregateRow;
|
||||
import me.iiv.agent.entity.m0.MonthlyStatistics;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.SelectProvider;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
public interface MonthlyStatisticsMapper extends BaseMapper<MonthlyStatistics> {
|
||||
|
||||
@SelectProvider(type = MonthlyStatisticsSqlProvider.class, method = "selectDeviceAverage")
|
||||
List<DeviceAverageAggregateRow> selectDeviceAverage(
|
||||
@Param("view") MonthlyStatisticsSqlProvider.View view,
|
||||
@Param("districtId") Long districtId,
|
||||
@Param("startAt") LocalDateTime startAt,
|
||||
@Param("endExclusive") LocalDateTime endExclusive,
|
||||
@Param("deviceType") Integer deviceType,
|
||||
@Param("buildingIds") List<Long> buildingIds,
|
||||
@Param("floors") List<String> floors,
|
||||
@Param("toiletIds") List<Long> toiletIds);
|
||||
}
|
||||
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
package me.iiv.agent.mapper.m0;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** monthly_statistics 受控聚合 SQL,只允许设备日均统计定义的五种分组。 */
|
||||
public class MonthlyStatisticsSqlProvider {
|
||||
|
||||
public String selectDeviceAverage(Map<String, Object> params) {
|
||||
View view = (View) params.get("view");
|
||||
if (view == null) {
|
||||
throw new IllegalArgumentException("view is required");
|
||||
}
|
||||
|
||||
StringBuilder sql = new StringBuilder("<script>SELECT ")
|
||||
.append(view.selectDimensions())
|
||||
.append(", SUM(COALESCE(paper_length, 0)) AS paper_length_cm")
|
||||
.append(", COUNT(*) AS record_count")
|
||||
.append(" FROM monthly_statistics")
|
||||
.append(" WHERE soft_delete = 0")
|
||||
.append(" AND district_id = #{districtId}")
|
||||
.append(" AND statistics_time >= #{startAt}")
|
||||
.append(" AND statistics_time < #{endExclusive}");
|
||||
|
||||
if (params.get("deviceType") != null) {
|
||||
sql.append(" AND device_type = #{deviceType}");
|
||||
}
|
||||
appendIn(sql, params, "buildingIds", "building_id", "buildingId");
|
||||
appendIn(sql, params, "floors", "floor", "floorValue");
|
||||
appendIn(sql, params, "toiletIds", "toilet_id", "toiletId");
|
||||
sql.append(" GROUP BY ").append(view.groupBy())
|
||||
.append(" ORDER BY ").append(view.orderBy())
|
||||
.append("</script>");
|
||||
return sql.toString();
|
||||
}
|
||||
|
||||
private static void appendIn(StringBuilder sql, Map<String, Object> params,
|
||||
String parameter, String column, String item) {
|
||||
Object value = params.get(parameter);
|
||||
if (!(value instanceof List<?>) || ((List<?>) value).isEmpty()) {
|
||||
return;
|
||||
}
|
||||
sql.append(" AND ").append(column).append(" IN ")
|
||||
.append("<foreach collection='").append(parameter)
|
||||
.append("' item='").append(item)
|
||||
.append("' open='(' separator=',' close=')'>#{")
|
||||
.append(item).append("}</foreach>");
|
||||
}
|
||||
|
||||
public enum View {
|
||||
GENDER("gender", "NULL AS statistics_date, NULL AS floor, gender AS gender_code",
|
||||
"gender", "gender"),
|
||||
DAILY_GENDER("daily_gender",
|
||||
"DATE(statistics_time) AS statistics_date, NULL AS floor, gender AS gender_code",
|
||||
"DATE(statistics_time), gender", "DATE(statistics_time), gender"),
|
||||
FLOOR("floor", "NULL AS statistics_date, floor, NULL AS gender_code",
|
||||
"floor", "floor"),
|
||||
DAILY_FLOOR("daily_floor",
|
||||
"DATE(statistics_time) AS statistics_date, floor, NULL AS gender_code",
|
||||
"DATE(statistics_time), floor", "DATE(statistics_time), floor"),
|
||||
FLOOR_GENDER("floor_gender", "NULL AS statistics_date, floor, gender AS gender_code",
|
||||
"floor, gender", "floor, gender");
|
||||
|
||||
private final String apiValue;
|
||||
private final String selectDimensions;
|
||||
private final String groupBy;
|
||||
private final String orderBy;
|
||||
|
||||
View(String apiValue, String selectDimensions, String groupBy, String orderBy) {
|
||||
this.apiValue = apiValue;
|
||||
this.selectDimensions = selectDimensions;
|
||||
this.groupBy = groupBy;
|
||||
this.orderBy = orderBy;
|
||||
}
|
||||
|
||||
public String apiValue() {
|
||||
return apiValue;
|
||||
}
|
||||
|
||||
public String selectDimensions() {
|
||||
return selectDimensions;
|
||||
}
|
||||
|
||||
public String groupBy() {
|
||||
return groupBy;
|
||||
}
|
||||
|
||||
public String orderBy() {
|
||||
return orderBy;
|
||||
}
|
||||
|
||||
public boolean includesDate() {
|
||||
return this == DAILY_GENDER || this == DAILY_FLOOR;
|
||||
}
|
||||
|
||||
public boolean includesFloor() {
|
||||
return this == FLOOR || this == DAILY_FLOOR || this == FLOOR_GENDER;
|
||||
}
|
||||
|
||||
public boolean includesGender() {
|
||||
return this == GENDER || this == DAILY_GENDER || this == FLOOR_GENDER;
|
||||
}
|
||||
|
||||
public static View fromApiValue(String value) {
|
||||
for (View view : values()) {
|
||||
if (view.apiValue.equals(value)) {
|
||||
return view;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+311
@@ -0,0 +1,311 @@
|
||||
package me.iiv.agent.mcp.tool;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import me.iiv.agent.entity.m0.DeviceAverageAggregateRow;
|
||||
import me.iiv.agent.entity.m0.DistrictDistrictStrategy;
|
||||
import me.iiv.agent.entity.m0.User;
|
||||
import me.iiv.agent.entity.svc.AgentApiKey;
|
||||
import me.iiv.agent.mapper.m0.DistrictDistrictStrategyMapper;
|
||||
import me.iiv.agent.mapper.m0.MonthlyStatisticsMapper;
|
||||
import me.iiv.agent.mapper.m0.MonthlyStatisticsSqlProvider;
|
||||
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.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** 设备日均用纸统计:覆盖老 StatisticsReportController 的五种硬件统计视图。 */
|
||||
@Component
|
||||
public class HardwareStatisticsTools implements ToolObject {
|
||||
|
||||
private static final String DICTIONARY_KEY = "Dictionary";
|
||||
private static final String DICT_STATISTICS_DAYS = "StatisticsDays";
|
||||
private static final ZoneId SHANGHAI = ZoneId.of("Asia/Shanghai");
|
||||
private static final BigDecimal CENTIMETERS_PER_METER = BigDecimal.valueOf(100);
|
||||
private static final String COUNT_NOTICE =
|
||||
"统计分母为 monthly_statistics 记录数 COUNT(*),不是使用人次 SUM(use_count)";
|
||||
|
||||
final DistrictDistrictStrategyMapper districtMapper;
|
||||
final MonthlyStatisticsMapper monthlyStatisticsMapper;
|
||||
final PermissionService permissionService;
|
||||
final StringRedisTemplate redisTemplate;
|
||||
|
||||
public HardwareStatisticsTools(DistrictDistrictStrategyMapper districtMapper,
|
||||
MonthlyStatisticsMapper monthlyStatisticsMapper,
|
||||
PermissionService permissionService,
|
||||
StringRedisTemplate redisTemplate) {
|
||||
this.districtMapper = districtMapper;
|
||||
this.monthlyStatisticsMapper = monthlyStatisticsMapper;
|
||||
this.permissionService = permissionService;
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
@XqTool(category = "hardware", kind = "read")
|
||||
@Tool(name = "district.paper.device_average.query", description = "查询站点设备日均用纸量。"
|
||||
+ "view 仅支持 gender、daily_gender、floor、daily_floor、floor_gender;"
|
||||
+ "返回统一 rows,每行包含日期、楼层、卫生间类型、用纸米数、统计记录数和设备日均值。"
|
||||
+ "分母固定为 monthly_statistics 的 COUNT(*),不是 SUM(use_count)。"
|
||||
+ "日期范围最大天数受 Redis Dictionary.StatisticsDays 限制。")
|
||||
public Map<String, Object> districtPaperDeviceAverageQuery(
|
||||
@ToolParam(description = "站点 id,正整数") Long districtId,
|
||||
@ToolParam(description = "开始日期,yyyy-MM-dd,含当天") String startDate,
|
||||
@ToolParam(description = "结束日期,yyyy-MM-dd,含当天,不得晚于今天") String endDate,
|
||||
@ToolParam(description = "视图:gender、daily_gender、floor、daily_floor、floor_gender") String view,
|
||||
@ToolParam(required = false, description = "设备类型:0=出纸机、1=擦手纸机,缺省不过滤") Integer deviceType,
|
||||
@ToolParam(required = false, description = "楼 id 列表;列表内 IN,与其他位置维度 AND")
|
||||
List<Long> buildingIds,
|
||||
@ToolParam(required = false, description = "楼层列表;列表内 IN,与其他位置维度 AND")
|
||||
List<String> floors,
|
||||
@ToolParam(required = false, description = "卫生间 id 列表;列表内 IN,与其他位置维度 AND")
|
||||
List<Long> toiletIds) {
|
||||
|
||||
if (districtId == null || districtId < 1) {
|
||||
throw invalid("districtId 必填且必须为正整数");
|
||||
}
|
||||
LocalDate start = parseDay(startDate, "startDate");
|
||||
LocalDate end = parseDay(endDate, "endDate");
|
||||
if (start.isAfter(end)) {
|
||||
throw invalid("startDate 不能晚于 endDate");
|
||||
}
|
||||
if (end.isAfter(LocalDate.now(SHANGHAI))) {
|
||||
throw invalid("endDate 不得晚于今天");
|
||||
}
|
||||
MonthlyStatisticsSqlProvider.View selectedView = MonthlyStatisticsSqlProvider.View.fromApiValue(view);
|
||||
if (selectedView == null) {
|
||||
throw invalid("view 仅支持 gender、daily_gender、floor、daily_floor、floor_gender");
|
||||
}
|
||||
if (deviceType != null && deviceType != 0 && deviceType != 1) {
|
||||
throw invalid("deviceType 仅支持 0、1");
|
||||
}
|
||||
List<Long> normalizedBuildingIds = positiveIds(buildingIds, "buildingIds");
|
||||
List<String> normalizedFloors = floorValues(floors);
|
||||
List<Long> normalizedToiletIds = positiveIds(toiletIds, "toiletIds");
|
||||
|
||||
AuthContext context = AuthContextHolder.get();
|
||||
if (context == null || (context.getUser() == null && !isServicePrincipal(context))) {
|
||||
throw new ToolCallException(McpErrorCode.UNAUTHENTICATED, "缺少有效身份上下文");
|
||||
}
|
||||
User user = context.getUser();
|
||||
DistrictDistrictStrategy district = visibleDistrict(districtId, user);
|
||||
|
||||
int maxDays = statisticsDays();
|
||||
int queryDays = (int) ChronoUnit.DAYS.between(start, end) + 1;
|
||||
if (queryDays > maxDays) {
|
||||
throw invalid("查询时间段最大" + maxDays + "天");
|
||||
}
|
||||
|
||||
List<DeviceAverageAggregateRow> aggregates;
|
||||
try {
|
||||
aggregates = monthlyStatisticsMapper.selectDeviceAverage(
|
||||
selectedView,
|
||||
districtId,
|
||||
start.atStartOfDay(),
|
||||
end.plusDays(1).atStartOfDay(),
|
||||
deviceType,
|
||||
normalizedBuildingIds,
|
||||
normalizedFloors,
|
||||
normalizedToiletIds);
|
||||
} catch (RuntimeException exception) {
|
||||
throw new ToolCallException(McpErrorCode.UPSTREAM_UNAVAILABLE, "设备用纸统计数据暂不可用");
|
||||
}
|
||||
|
||||
return response(district, start, end, queryDays, selectedView,
|
||||
aggregates == null ? List.of() : aggregates);
|
||||
}
|
||||
|
||||
private DistrictDistrictStrategy visibleDistrict(Long districtId, User user) {
|
||||
try {
|
||||
LambdaQueryWrapper<DistrictDistrictStrategy> wrapper =
|
||||
new LambdaQueryWrapper<DistrictDistrictStrategy>()
|
||||
.eq(DistrictDistrictStrategy::getSoftDelete, 0)
|
||||
.eq(DistrictDistrictStrategy::getId, districtId);
|
||||
permissionService.applyDistrictRowFilter(wrapper, user);
|
||||
DistrictDistrictStrategy district = districtMapper.selectOne(wrapper);
|
||||
if (district == null) {
|
||||
throw new ToolCallException(McpErrorCode.NOT_FOUND_OR_FORBIDDEN,
|
||||
"站点不存在或无权访问");
|
||||
}
|
||||
return district;
|
||||
} catch (ToolCallException exception) {
|
||||
throw exception;
|
||||
} catch (RuntimeException exception) {
|
||||
throw new ToolCallException(McpErrorCode.UPSTREAM_UNAVAILABLE, "站点权限数据暂不可用");
|
||||
}
|
||||
}
|
||||
|
||||
private int statisticsDays() {
|
||||
Object value;
|
||||
try {
|
||||
value = redisTemplate.opsForHash().get(DICTIONARY_KEY, DICT_STATISTICS_DAYS);
|
||||
} catch (RuntimeException exception) {
|
||||
throw new ToolCallException(McpErrorCode.UPSTREAM_UNAVAILABLE, "统计日期配置暂不可用");
|
||||
}
|
||||
if (value == null) {
|
||||
throw new ToolCallException(McpErrorCode.UPSTREAM_UNAVAILABLE,
|
||||
"Redis Dictionary 缺少 StatisticsDays 字段");
|
||||
}
|
||||
try {
|
||||
int days = Integer.parseInt(value.toString().trim());
|
||||
if (days < 1) {
|
||||
throw new NumberFormatException("non-positive");
|
||||
}
|
||||
return days;
|
||||
} catch (NumberFormatException exception) {
|
||||
throw new ToolCallException(McpErrorCode.UPSTREAM_UNAVAILABLE,
|
||||
"Redis Dictionary.StatisticsDays 必须为正整数");
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> response(DistrictDistrictStrategy district,
|
||||
LocalDate start,
|
||||
LocalDate end,
|
||||
int queryDays,
|
||||
MonthlyStatisticsSqlProvider.View view,
|
||||
List<DeviceAverageAggregateRow> aggregates) {
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
BigDecimal totalPaperLengthCm = BigDecimal.ZERO;
|
||||
long totalRecordCount = 0L;
|
||||
for (DeviceAverageAggregateRow aggregate : aggregates) {
|
||||
validateAggregate(aggregate);
|
||||
totalPaperLengthCm = totalPaperLengthCm.add(aggregate.getPaperLengthCm());
|
||||
totalRecordCount += aggregate.getRecordCount();
|
||||
rows.add(resultRow(aggregate, view));
|
||||
}
|
||||
|
||||
Map<String, Object> dateRange = new LinkedHashMap<>();
|
||||
dateRange.put("startDate", start.toString());
|
||||
dateRange.put("endDate", end.toString());
|
||||
dateRange.put("days", queryDays);
|
||||
|
||||
Map<String, Object> summary = new LinkedHashMap<>();
|
||||
summary.put("paperLengthMeters", meters(totalPaperLengthCm));
|
||||
summary.put("recordCount", totalRecordCount);
|
||||
summary.put("averagePaperMeters", totalRecordCount == 0
|
||||
? null : average(totalPaperLengthCm, totalRecordCount));
|
||||
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("districtId", district.getId());
|
||||
result.put("districtName", district.getDistrictName());
|
||||
result.put("dateRange", dateRange);
|
||||
result.put("view", view.apiValue());
|
||||
result.put("unit", "米/设备日统计记录");
|
||||
result.put("summary", summary);
|
||||
result.put("total", rows.size());
|
||||
result.put("rows", rows);
|
||||
result.put("notice", rows.isEmpty() ? COUNT_NOTICE + ";当前条件无数据" : COUNT_NOTICE);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Map<String, Object> resultRow(DeviceAverageAggregateRow aggregate,
|
||||
MonthlyStatisticsSqlProvider.View view) {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("date", view.includesDate() && aggregate.getStatisticsDate() != null
|
||||
? aggregate.getStatisticsDate().toString() : null);
|
||||
row.put("floor", view.includesFloor() ? aggregate.getFloor() : null);
|
||||
row.put("genderCode", view.includesGender() ? aggregate.getGenderCode() : null);
|
||||
row.put("gender", view.includesGender() ? genderText(aggregate.getGenderCode()) : null);
|
||||
row.put("paperLengthMeters", meters(aggregate.getPaperLengthCm()));
|
||||
row.put("recordCount", aggregate.getRecordCount());
|
||||
row.put("averagePaperMeters", average(aggregate.getPaperLengthCm(), aggregate.getRecordCount()));
|
||||
return row;
|
||||
}
|
||||
|
||||
private static void validateAggregate(DeviceAverageAggregateRow aggregate) {
|
||||
if (aggregate == null || aggregate.getPaperLengthCm() == null
|
||||
|| aggregate.getPaperLengthCm().signum() < 0
|
||||
|| aggregate.getRecordCount() == null || aggregate.getRecordCount() < 1) {
|
||||
throw new ToolCallException(McpErrorCode.DATA_INTEGRITY_ERROR, "设备用纸聚合结果异常");
|
||||
}
|
||||
}
|
||||
|
||||
private static BigDecimal meters(BigDecimal centimeters) {
|
||||
return centimeters.divide(CENTIMETERS_PER_METER, 2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private static BigDecimal average(BigDecimal centimeters, long recordCount) {
|
||||
return centimeters.divide(CENTIMETERS_PER_METER.multiply(BigDecimal.valueOf(recordCount)),
|
||||
2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private static List<Long> positiveIds(List<Long> values, String name) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
LinkedHashSet<Long> normalized = new LinkedHashSet<>();
|
||||
for (Long value : values) {
|
||||
if (value == null || value < 1) {
|
||||
throw invalid(name + " 每项必须为正整数");
|
||||
}
|
||||
normalized.add(value);
|
||||
}
|
||||
return new ArrayList<>(normalized);
|
||||
}
|
||||
|
||||
private static List<String> floorValues(List<String> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
LinkedHashSet<String> normalized = new LinkedHashSet<>();
|
||||
for (String value : values) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
throw invalid("floors 每项不得为空");
|
||||
}
|
||||
normalized.add(value.trim());
|
||||
}
|
||||
return new ArrayList<>(normalized);
|
||||
}
|
||||
|
||||
private static LocalDate parseDay(String value, String name) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
throw invalid(name + " 必填,格式 yyyy-MM-dd");
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(value.trim());
|
||||
} catch (DateTimeParseException exception) {
|
||||
throw invalid(name + " 格式非法,要求 yyyy-MM-dd: " + value);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isServicePrincipal(AuthContext context) {
|
||||
return context.getToken() != null
|
||||
&& AgentApiKey.PRINCIPAL_TYPE_SERVICE.equals(context.getToken().getPrincipalType());
|
||||
}
|
||||
|
||||
private static ToolCallException invalid(String message) {
|
||||
return new ToolCallException(McpErrorCode.INVALID_ARGUMENT, message);
|
||||
}
|
||||
|
||||
private static String genderText(Integer gender) {
|
||||
if (gender == null) {
|
||||
return "未配置";
|
||||
}
|
||||
return switch (gender) {
|
||||
case 0 -> "男卫";
|
||||
case 1 -> "女卫";
|
||||
case 2 -> "母婴室";
|
||||
case 3 -> "无障碍";
|
||||
case 4 -> "第三卫";
|
||||
case 5 -> "其他";
|
||||
default -> "未知(" + gender + ")";
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user