feat(mcp): 新增人均用纸统计工具 (REQ-20260922-0004)
This commit is contained in:
+310
@@ -0,0 +1,310 @@
|
||||
package me.iiv.agent.mcp.tool;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import me.iiv.agent.entity.m0.DistrictDistrictStrategy;
|
||||
import me.iiv.agent.entity.m0.MonthlyStatistics;
|
||||
import me.iiv.agent.entity.m0.User;
|
||||
import me.iiv.agent.mapper.m0.DistrictDistrictStrategyMapper;
|
||||
import me.iiv.agent.mapper.m0.MonthlyStatisticsMapper;
|
||||
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.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.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/** 人均用纸统计:覆盖老 StatisticsReportController 的五种分组查询。 */
|
||||
@Component
|
||||
public class PaperPerCapitaStatisticsTools 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 Set<String> GROUPS = Set.of("gender", "floor", "floorGender");
|
||||
|
||||
final DistrictDistrictStrategyMapper districtMapper;
|
||||
final MonthlyStatisticsMapper monthlyStatisticsMapper;
|
||||
final PermissionService permissionService;
|
||||
final StringRedisTemplate redisTemplate;
|
||||
|
||||
public PaperPerCapitaStatisticsTools(DistrictDistrictStrategyMapper districtMapper,
|
||||
MonthlyStatisticsMapper monthlyStatisticsMapper,
|
||||
PermissionService permissionService,
|
||||
StringRedisTemplate redisTemplate) {
|
||||
this.districtMapper = districtMapper;
|
||||
this.monthlyStatisticsMapper = monthlyStatisticsMapper;
|
||||
this.permissionService = permissionService;
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
@XqTool(category = "district", kind = "read")
|
||||
@Tool(name = "district.paper.percapita.query", description = "查询站点人均用纸统计。"
|
||||
+ "用 groupBy=gender/floor/floorGender 选择性别、楼层或楼层与卫生间类型分组;"
|
||||
+ "daily=true 时再按日分组,仅支持 gender 和 floor。"
|
||||
+ "返回面向 LLM 的扁平 rows,每行含 date、floor、gender、paperLengthMeters、useCount、perCapita;"
|
||||
+ "没有数据的日期或分组不会补 0。paperLengthMeters 单位为米,perCapita 单位为米/人次。"
|
||||
+ "日期范围最大天数受 Redis Dictionary.StatisticsDays 限制。")
|
||||
public Map<String, Object> districtPaperPerCapitaQuery(
|
||||
@ToolParam(description = "站点 id,正整数") Long districtId,
|
||||
@ToolParam(description = "开始日期,yyyy-MM-dd,含当天") String startDate,
|
||||
@ToolParam(description = "结束日期,yyyy-MM-dd,含当天,不得晚于今天") String endDate,
|
||||
@ToolParam(description = "分组:gender、floor、floorGender") String groupBy,
|
||||
@ToolParam(required = false, description = "是否按日分组,默认 false;floorGender 不支持 true") Boolean daily,
|
||||
@ToolParam(required = false, description = "设备类型:0=出纸机、1=擦手纸机,缺省不过滤") Integer deviceType,
|
||||
@ToolParam(required = false, description = "位置列表,每项格式 buildingId_floor_toiletId;三列分别独立 IN 过滤")
|
||||
List<String> idStrList) {
|
||||
|
||||
if (districtId == null) {
|
||||
throw new IllegalArgumentException("districtId 必填");
|
||||
}
|
||||
if (districtId < 1) {
|
||||
throw new IllegalArgumentException("districtId 必须为正整数");
|
||||
}
|
||||
LocalDate start = parseDay(startDate, "startDate");
|
||||
LocalDate end = parseDay(endDate, "endDate");
|
||||
LocalDate today = LocalDate.now(SHANGHAI);
|
||||
if (start.isAfter(end)) {
|
||||
throw new IllegalArgumentException("startDate 不能晚于 endDate");
|
||||
}
|
||||
if (end.isAfter(today)) {
|
||||
throw new IllegalArgumentException("endDate 不得晚于今天");
|
||||
}
|
||||
if (!StringUtils.hasText(groupBy) || !GROUPS.contains(groupBy)) {
|
||||
throw new IllegalArgumentException("groupBy 仅支持 gender、floor、floorGender");
|
||||
}
|
||||
boolean byDay = Boolean.TRUE.equals(daily);
|
||||
if (byDay && "floorGender".equals(groupBy)) {
|
||||
throw new IllegalArgumentException("floorGender 不支持 daily=true");
|
||||
}
|
||||
if (deviceType != null && deviceType != 0 && deviceType != 1) {
|
||||
throw new IllegalArgumentException("deviceType 仅支持 0、1");
|
||||
}
|
||||
PositionFilters filters = parsePositionFilters(idStrList);
|
||||
|
||||
User user = AuthContextHolder.get().getUser();
|
||||
LambdaQueryWrapper<DistrictDistrictStrategy> districtWrapper =
|
||||
new LambdaQueryWrapper<DistrictDistrictStrategy>()
|
||||
.eq(DistrictDistrictStrategy::getSoftDelete, 0)
|
||||
.eq(DistrictDistrictStrategy::getId, districtId);
|
||||
permissionService.applyDistrictRowFilter(districtWrapper, user);
|
||||
DistrictDistrictStrategy district = districtMapper.selectOne(districtWrapper);
|
||||
if (district == null) {
|
||||
throw new IllegalStateException("站点不存在或无权访问");
|
||||
}
|
||||
|
||||
int maxDays = statisticsDays();
|
||||
int queryDays = (int) ChronoUnit.DAYS.between(start, end) + 1;
|
||||
if (queryDays > maxDays) {
|
||||
throw new IllegalArgumentException("查询时间段最大" + maxDays + "天");
|
||||
}
|
||||
|
||||
List<MonthlyStatistics> sourceRows = queryRows(districtId, start, end, deviceType, filters);
|
||||
Map<GroupKey, Aggregate> aggregates = aggregate(sourceRows, groupBy, byDay);
|
||||
List<Map<String, Object>> resultRows = toResultRows(aggregates);
|
||||
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("districtId", districtId);
|
||||
result.put("districtName", district.getDistrictName());
|
||||
result.put("dateRange", start + " ~ " + end);
|
||||
result.put("unit", "米/人次");
|
||||
result.put("groupBy", groupBy);
|
||||
result.put("daily", byDay);
|
||||
result.put("totalPerCapita", byDay ? null : totalPerCapita(aggregates));
|
||||
result.put("rows", resultRows);
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<MonthlyStatistics> queryRows(Long districtId, LocalDate start, LocalDate end,
|
||||
Integer deviceType, PositionFilters filters) {
|
||||
LambdaQueryWrapper<MonthlyStatistics> wrapper = new LambdaQueryWrapper<MonthlyStatistics>()
|
||||
.eq(MonthlyStatistics::getSoftDelete, 0)
|
||||
.eq(MonthlyStatistics::getDistrictId, districtId)
|
||||
.ge(MonthlyStatistics::getStatisticsTime,
|
||||
Date.from(start.atStartOfDay(SHANGHAI).toInstant()))
|
||||
.lt(MonthlyStatistics::getStatisticsTime,
|
||||
Date.from(end.plusDays(1).atStartOfDay(SHANGHAI).toInstant()));
|
||||
if (deviceType != null) {
|
||||
wrapper.eq(MonthlyStatistics::getDeviceType, deviceType);
|
||||
}
|
||||
if (!filters.buildingIds.isEmpty()) {
|
||||
wrapper.in(MonthlyStatistics::getBuildingId, filters.buildingIds);
|
||||
}
|
||||
if (!filters.floors.isEmpty()) {
|
||||
wrapper.in(MonthlyStatistics::getFloor, filters.floors);
|
||||
}
|
||||
if (!filters.toiletIds.isEmpty()) {
|
||||
wrapper.in(MonthlyStatistics::getToiletId, filters.toiletIds);
|
||||
}
|
||||
return monthlyStatisticsMapper.selectList(wrapper);
|
||||
}
|
||||
|
||||
private Map<GroupKey, Aggregate> aggregate(List<MonthlyStatistics> rows, String groupBy, boolean daily) {
|
||||
Comparator<GroupKey> comparator = Comparator
|
||||
.comparing((GroupKey key) -> key.date, Comparator.nullsFirst(Comparator.naturalOrder()))
|
||||
.thenComparing(key -> key.floor, Comparator.nullsFirst(Comparator.naturalOrder()))
|
||||
.thenComparing(key -> key.gender, Comparator.nullsFirst(Comparator.naturalOrder()));
|
||||
Map<GroupKey, Aggregate> result = new TreeMap<>(comparator);
|
||||
for (MonthlyStatistics row : rows) {
|
||||
String date = null;
|
||||
if (daily) {
|
||||
if (row.getStatisticsTime() == null) {
|
||||
continue;
|
||||
}
|
||||
date = row.getStatisticsTime().toInstant().atZone(SHANGHAI).toLocalDate().toString();
|
||||
}
|
||||
String floor = null;
|
||||
if ("floor".equals(groupBy) || "floorGender".equals(groupBy)) {
|
||||
if (!StringUtils.hasText(row.getFloor())) {
|
||||
continue;
|
||||
}
|
||||
floor = row.getFloor();
|
||||
}
|
||||
Integer gender = null;
|
||||
if ("gender".equals(groupBy) || "floorGender".equals(groupBy)) {
|
||||
if (row.getGender() == null) {
|
||||
continue;
|
||||
}
|
||||
gender = row.getGender();
|
||||
}
|
||||
GroupKey key = new GroupKey(date, floor, gender);
|
||||
Aggregate value = result.computeIfAbsent(key, ignored -> new Aggregate());
|
||||
value.paperLengthCm += row.getPaperLength() == null ? 0L : row.getPaperLength();
|
||||
value.useCount += row.getUseCount() == null ? 0L : row.getUseCount();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> toResultRows(Map<GroupKey, Aggregate> aggregates) {
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
for (Map.Entry<GroupKey, Aggregate> entry : aggregates.entrySet()) {
|
||||
GroupKey key = entry.getKey();
|
||||
Aggregate value = entry.getValue();
|
||||
double paperLengthMeters = value.paperLengthCm / 100.0;
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("date", key.date);
|
||||
row.put("floor", key.floor);
|
||||
row.put("gender", key.gender == null ? null : genderText(key.gender));
|
||||
row.put("paperLengthMeters", round2(paperLengthMeters));
|
||||
row.put("useCount", value.useCount);
|
||||
row.put("perCapita", value.useCount > 0
|
||||
? round2(paperLengthMeters / value.useCount)
|
||||
: round2(paperLengthMeters));
|
||||
rows.add(row);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
private Double totalPerCapita(Map<GroupKey, Aggregate> aggregates) {
|
||||
long paperLengthCm = aggregates.values().stream().mapToLong(value -> value.paperLengthCm).sum();
|
||||
long useCount = aggregates.values().stream().mapToLong(value -> value.useCount).sum();
|
||||
double paperLengthMeters = paperLengthCm / 100.0;
|
||||
return useCount > 0 ? round2(paperLengthMeters / useCount) : round2(paperLengthMeters);
|
||||
}
|
||||
|
||||
private int statisticsDays() {
|
||||
Object value = redisTemplate.opsForHash().get(DICTIONARY_KEY, DICT_STATISTICS_DAYS);
|
||||
if (value == null) {
|
||||
throw new IllegalStateException("Redis Dictionary 缺少 StatisticsDays 字段,拒绝查询");
|
||||
}
|
||||
try {
|
||||
int days = Integer.parseInt(value.toString().trim());
|
||||
if (days < 1) {
|
||||
throw new NumberFormatException("non-positive");
|
||||
}
|
||||
return days;
|
||||
} catch (NumberFormatException e) {
|
||||
throw new IllegalStateException("Redis Dictionary.StatisticsDays 必须为正整数");
|
||||
}
|
||||
}
|
||||
|
||||
private static PositionFilters parsePositionFilters(List<String> values) {
|
||||
PositionFilters filters = new PositionFilters();
|
||||
if (values == null || values.isEmpty()) {
|
||||
return filters;
|
||||
}
|
||||
for (String value : values) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
throw new IllegalArgumentException("idStrList 每项必须为 buildingId_floor_toiletId");
|
||||
}
|
||||
String[] parts = value.trim().split("_", -1);
|
||||
if (parts.length != 3 || !StringUtils.hasText(parts[1])) {
|
||||
throw new IllegalArgumentException("idStrList 每项必须为 buildingId_floor_toiletId: " + value);
|
||||
}
|
||||
filters.buildingIds.add(parsePositiveId(parts[0], "buildingId", value));
|
||||
filters.floors.add(parts[1].trim());
|
||||
filters.toiletIds.add(parsePositiveId(parts[2], "toiletId", value));
|
||||
}
|
||||
return filters;
|
||||
}
|
||||
|
||||
private static Long parsePositiveId(String value, String name, String source) {
|
||||
try {
|
||||
long id = Long.parseLong(value.trim());
|
||||
if (id < 1) {
|
||||
throw new NumberFormatException("non-positive");
|
||||
}
|
||||
return id;
|
||||
} catch (NumberFormatException e) {
|
||||
throw new IllegalArgumentException("idStrList 中 " + name + " 必须为正整数: " + source);
|
||||
}
|
||||
}
|
||||
|
||||
private static LocalDate parseDay(String value, String name) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
throw new IllegalArgumentException(name + " 必填,格式 yyyy-MM-dd");
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(value.trim());
|
||||
} catch (java.time.format.DateTimeParseException e) {
|
||||
throw new IllegalArgumentException(name + " 格式非法,要求 yyyy-MM-dd: " + value);
|
||||
}
|
||||
}
|
||||
|
||||
private static double round2(double value) {
|
||||
return BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_UP).doubleValue();
|
||||
}
|
||||
|
||||
private static String genderText(Integer gender) {
|
||||
switch (gender) {
|
||||
case 0: return "男卫";
|
||||
case 1: return "女卫";
|
||||
case 2: return "母婴室";
|
||||
case 3: return "无障碍";
|
||||
case 4: return "第三卫";
|
||||
case 5: return "其他";
|
||||
default: return "未知";
|
||||
}
|
||||
}
|
||||
|
||||
private static final class PositionFilters {
|
||||
final Set<Long> buildingIds = new LinkedHashSet<>();
|
||||
final Set<String> floors = new LinkedHashSet<>();
|
||||
final Set<Long> toiletIds = new LinkedHashSet<>();
|
||||
}
|
||||
|
||||
private static final class Aggregate {
|
||||
long paperLengthCm;
|
||||
long useCount;
|
||||
}
|
||||
|
||||
private record GroupKey(String date, String floor, Integer gender) {
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user