@@ -0,0 +1,360 @@
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.Positions ;
import me.iiv.agent.entity.m0.Toilet ;
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.mapper.m0.PositionsMapper ;
import me.iiv.agent.mapper.m0.ToiletMapper ;
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.HashMap ;
import java.util.LinkedHashMap ;
import java.util.LinkedHashSet ;
import java.util.List ;
import java.util.Map ;
import java.util.Set ;
import java.util.TreeMap ;
import java.util.TreeSet ;
/**
* 客户用纸详情(老 MonthlyStatisticsController.getMonthlyStatisticsPerPositionMap 复刻):
* 纯 DB 聚合 m0 monthly_statistics,按 位置(厕位/厕墙)× 日期 分组,
* 输出扁平行(用纸长度米/人次/人均米/涉及 SN)。位置命名直查 m0 positions/toilet 表。
* 设计文档:doc/paper-position-detail-mcp-design.md
*/
@Component
public class DistrictPaperPositionDetailTools implements ToolObject {
private static final String DICTIONARY_KEY = " Dictionary " ;
private static final String DICT_STATISTICS_DAYS = " StatisticsDays " ;
/** 日期区间硬限一个月(2026-09-24 用户拍板),与 Redis StatisticsDays 取更严 */
private static final int MAX_QUERY_DAYS = 31 ;
private static final ZoneId SHANGHAI = ZoneId . of ( " Asia/Shanghai " ) ;
private static final String UNKNOWN_NAME = " 未知 " ;
final DistrictDistrictStrategyMapper districtMapper ;
final MonthlyStatisticsMapper monthlyStatisticsMapper ;
final PositionsMapper positionsMapper ;
final ToiletMapper toiletMapper ;
final PermissionService permissionService ;
final StringRedisTemplate redisTemplate ;
public DistrictPaperPositionDetailTools ( DistrictDistrictStrategyMapper districtMapper ,
MonthlyStatisticsMapper monthlyStatisticsMapper ,
PositionsMapper positionsMapper ,
ToiletMapper toiletMapper ,
PermissionService permissionService ,
StringRedisTemplate redisTemplate ) {
this . districtMapper = districtMapper ;
this . monthlyStatisticsMapper = monthlyStatisticsMapper ;
this . positionsMapper = positionsMapper ;
this . toiletMapper = toiletMapper ;
this . permissionService = permissionService ;
this . redisTemplate = redisTemplate ;
}
@XqTool ( category = " district " , kind = " read " )
@Tool ( name = " district.paper.position.detail.query " , description = " 客户用纸详情:按站点和日期范围查询 "
+ " 每个位置(厕位/厕墙)每天的用纸明细——用纸长度(米)、使用人次、人均用纸(米/人次)与涉及设备 SN。 "
+ " 数据来自 m0 monthly_statistics 日汇总表,纯 MySQL 查询。返回扁平 rows, "
+ " 每行含 date、locationType( position=厕位/wall=厕墙)、positionId、toiletId、locationName、 "
+ " gender、genderText、snCodes、paperLengthMeters、useCount、perUseLengthMeters; "
+ " 没有数据的日期与位置不出行、不补 0;厕墙行 useCount 恒 0、perUseLengthMeters 为 null。 "
+ " 日期区间最长 31 天(一个月),且受 Redis Dictionary.StatisticsDays 限制。 " )
public Map < String , Object > districtPaperPositionDetailQuery (
@ToolParam ( description = " 站点 id,正整数 " ) Long districtId ,
@ToolParam ( description = " 开始日期,yyyy-MM-dd,含当天 " ) String startDate ,
@ToolParam ( description = " 结束日期,yyyy-MM-dd,含当天,不得晚于今天 " ) String endDate ,
@ToolParam ( required = false , description = " 位置过滤:position=仅厕位、wall=仅厕墙,缺省不过滤 " ) String positionMode ,
@ToolParam ( required = false , description = " 设备类型:0=出纸机、1=擦手纸机,缺省不过滤 " ) Integer deviceType ,
@ToolParam ( required = false , description = " 楼 id,正整数,精确匹配 " ) Long buildingId ,
@ToolParam ( required = false , description = " 楼层,精确匹配 " ) String floor ,
@ToolParam ( required = false , description = " 厕所 id,正整数,精确匹配 " ) Long toiletId ) {
if ( districtId = = null ) {
throw new IllegalArgumentException ( " districtId 必填 " ) ;
}
validatePositive ( districtId , " districtId " ) ;
validatePositive ( buildingId , " buildingId " ) ;
validatePositive ( toiletId , " toiletId " ) ;
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 ( positionMode ) & & ! " position " . equals ( positionMode ) & & ! " wall " . equals ( positionMode ) ) {
throw new IllegalArgumentException ( " positionMode 仅支持 position、wall " ) ;
}
if ( deviceType ! = null & & deviceType ! = 0 & & deviceType ! = 1 ) {
throw new IllegalArgumentException ( " deviceType 仅支持 0、1 " ) ;
}
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 queryDays = ( int ) ChronoUnit . DAYS . between ( start , end ) + 1 ;
if ( queryDays > MAX_QUERY_DAYS ) {
throw new IllegalArgumentException (
" 查询时间段最长 " + MAX_QUERY_DAYS + " 天(一个月),请修改日期范围 " ) ;
}
int maxDays = statisticsDays ( ) ;
if ( queryDays > maxDays ) {
throw new IllegalArgumentException ( " 查询时间段最大 " + maxDays + " 天 " ) ;
}
List < MonthlyStatistics > sourceRows = queryRows ( districtId , start , end ,
positionMode , deviceType , buildingId , floor , toiletId ) ;
Map < GroupKey , Aggregate > aggregates = aggregate ( sourceRows ) ;
List < Map < String , Object > > rows = toResultRows ( aggregates ) ;
Map < String , Object > dateRange = new LinkedHashMap < > ( ) ;
dateRange . put ( " start " , start . toString ( ) ) ;
dateRange . put ( " end " , end . toString ( ) ) ;
Map < String , Object > result = new LinkedHashMap < > ( ) ;
result . put ( " districtId " , districtId ) ;
result . put ( " districtName " , district . getDistrictName ( ) ) ;
result . put ( " dateRange " , dateRange ) ;
result . put ( " unit " , " 米/人次 " ) ;
result . put ( " rows " , rows ) ;
return result ;
}
private List < MonthlyStatistics > queryRows ( Long districtId , LocalDate start , LocalDate end ,
String positionMode , Integer deviceType ,
Long buildingId , String floor , Long toiletId ) {
LambdaQueryWrapper < MonthlyStatistics > wrapper = new LambdaQueryWrapper < MonthlyStatistics > ( )
. eq ( MonthlyStatistics : : getSoftDelete , 0 )
. eq ( MonthlyStatistics : : getDistrictId , districtId )
. ge ( MonthlyStatistics : : getStatisticsTime ,
Date . from ( start . atStartOfDay ( SHANGHAI ) . toInstant ( ) ) )
// [start 00:00:00, end 23:59:59],用左闭右开避免秒精度丢行
. lt ( MonthlyStatistics : : getStatisticsTime ,
Date . from ( end . plusDays ( 1 ) . atStartOfDay ( SHANGHAI ) . toInstant ( ) ) ) ;
if ( " position " . equals ( positionMode ) ) {
wrapper . gt ( MonthlyStatistics : : getPositionId , 0 ) ;
} else if ( " wall " . equals ( positionMode ) ) {
wrapper . and ( w - > w . isNull ( MonthlyStatistics : : getPositionId )
. or ( ) . le ( MonthlyStatistics : : getPositionId , 0 ) ) ;
}
if ( deviceType ! = null ) {
wrapper . eq ( MonthlyStatistics : : getDeviceType , deviceType ) ;
}
if ( buildingId ! = null ) {
wrapper . eq ( MonthlyStatistics : : getBuildingId , buildingId ) ;
}
if ( StringUtils . hasText ( floor ) ) {
wrapper . eq ( MonthlyStatistics : : getFloor , floor ) ;
}
if ( toiletId ! = null ) {
wrapper . eq ( MonthlyStatistics : : getToiletId , toiletId ) ;
}
return monthlyStatisticsMapper . selectList ( wrapper ) ;
}
/** 老 :435-475 分组:位置(position_id>0 厕位 / 否则厕墙)× 日期;用纸全程 Double(修老 :452 整数除法截断) */
private Map < GroupKey , Aggregate > aggregate ( List < MonthlyStatistics > sourceRows ) {
Comparator < GroupKey > comparator = Comparator
. comparing ( ( GroupKey key ) - > key . date )
. thenComparing ( key - > key . locationType )
. thenComparing ( key - > key . locationId , Comparator . nullsLast ( Comparator . naturalOrder ( ) ) )
. thenComparing ( key - > key . toiletId , Comparator . nullsLast ( Comparator . naturalOrder ( ) ) ) ;
Map < GroupKey , Aggregate > result = new TreeMap < > ( comparator ) ;
for ( MonthlyStatistics row : sourceRows ) {
if ( row . getStatisticsTime ( ) = = null ) {
continue ;
}
String date = row . getStatisticsTime ( ) . toInstant ( ) . atZone ( SHANGHAI ) . toLocalDate ( ) . toString ( ) ;
boolean positionRow = row . getPositionId ( ) ! = null & & row . getPositionId ( ) > 0 ;
GroupKey key = positionRow
? new GroupKey ( date , " position " , row . getPositionId ( ) , row . getToiletId ( ) )
: new GroupKey ( date , " wall " , null , row . getToiletId ( ) ) ;
Aggregate value = result . computeIfAbsent ( key , ignored - > new Aggregate ( ) ) ;
value . paperLengthCm + = row . getPaperLength ( ) = = null ? 0L : row . getPaperLength ( ) ;
// useCount 仅厕位行累计,厕墙行表内恒 0(老 :454-456)
if ( positionRow & & row . getUseCount ( ) ! = null ) {
value . useCount + = row . getUseCount ( ) ;
}
if ( StringUtils . hasText ( row . getSnCode ( ) ) ) {
value . snCodes . add ( row . getSnCode ( ) ) ;
}
if ( value . gender = = null ) {
value . gender = row . getGender ( ) ;
}
}
return result ;
}
private List < Map < String , Object > > toResultRows ( Map < GroupKey , Aggregate > aggregates ) {
Map < Long , String > positionNames = loadPositionNames ( aggregates ) ;
Map < Long , String > toiletNames = loadToiletNames ( aggregates ) ;
List < Map < String , Object > > rows = new ArrayList < > ( ) ;
for ( Map . Entry < GroupKey , Aggregate > entry : aggregates . entrySet ( ) ) {
GroupKey key = entry . getKey ( ) ;
Aggregate value = entry . getValue ( ) ;
boolean positionRow = " position " . equals ( key . locationType ) ;
double paperLengthMeters = value . paperLengthCm / 100 . 0 ;
Map < String , Object > row = new LinkedHashMap < > ( ) ;
row . put ( " date " , key . date ) ;
row . put ( " locationType " , key . locationType ) ;
row . put ( " positionId " , positionRow ? key . locationId : null ) ;
row . put ( " toiletId " , key . toiletId ) ;
row . put ( " locationName " , positionRow
? positionNames . getOrDefault ( key . locationId , UNKNOWN_NAME )
: toiletNames . getOrDefault ( key . toiletId , UNKNOWN_NAME ) ) ;
row . put ( " gender " , value . gender ) ;
row . put ( " genderText " , genderText ( value . gender ) ) ;
row . put ( " snCodes " , new ArrayList < > ( value . snCodes ) ) ;
row . put ( " paperLengthMeters " , round2 ( paperLengthMeters ) ) ;
row . put ( " useCount " , value . useCount ) ;
// 厕墙人均不适用(useCount 恒 0 时为 null,区分"0"与"不适用")
row . put ( " perUseLengthMeters " , value . useCount > 0
? round2 ( paperLengthMeters / value . useCount ) : null ) ;
rows . add ( row ) ;
}
return rows ;
}
private Map < Long , String > loadPositionNames ( Map < GroupKey , Aggregate > aggregates ) {
Set < Long > ids = new LinkedHashSet < > ( ) ;
for ( GroupKey key : aggregates . keySet ( ) ) {
if ( " position " . equals ( key . locationType ) & & key . locationId ! = null ) {
ids . add ( key . locationId ) ;
}
}
Map < Long , String > names = new HashMap < > ( ) ;
if ( ids . isEmpty ( ) ) {
return names ;
}
List < Positions > positions = positionsMapper . selectList ( new LambdaQueryWrapper < Positions > ( )
. eq ( Positions : : getSoftDelete , 0 )
. in ( Positions : : getId , ids ) ) ;
for ( Positions position : positions ) {
names . put ( position . getId ( ) , firstText ( position . getMemo ( ) , position . getName ( ) ) ) ;
}
return names ;
}
private Map < Long , String > loadToiletNames ( Map < GroupKey , Aggregate > aggregates ) {
Set < Long > ids = new LinkedHashSet < > ( ) ;
for ( GroupKey key : aggregates . keySet ( ) ) {
if ( " wall " . equals ( key . locationType ) & & key . toiletId ! = null ) {
ids . add ( key . toiletId ) ;
}
}
Map < Long , String > names = new HashMap < > ( ) ;
if ( ids . isEmpty ( ) ) {
return names ;
}
List < Toilet > toilets = toiletMapper . selectList ( new LambdaQueryWrapper < Toilet > ( )
. eq ( Toilet : : getSoftDelete , 0 )
. in ( Toilet : : getId , ids ) ) ;
for ( Toilet toilet : toilets ) {
names . put ( toilet . getId ( ) , firstText ( toilet . getNo ( ) , toilet . getName ( ) ) ) ;
}
return names ;
}
private static String firstText ( String primary , String fallback ) {
if ( StringUtils . hasText ( primary ) ) {
return primary ;
}
return StringUtils . hasText ( fallback ) ? fallback : UNKNOWN_NAME ;
}
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 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 void validatePositive ( Long value , String name ) {
if ( value ! = null & & value < 1 ) {
throw new IllegalArgumentException ( name + " 必须为正整数 " ) ;
}
}
private static double round2 ( double value ) {
return BigDecimal . valueOf ( value ) . setScale ( 2 , RoundingMode . HALF_UP ) . doubleValue ( ) ;
}
/** gender 透传库内原值;0男卫/1女卫/2母婴/3残卫/4第三/5其他,99 及未知编码 genderText 为 null */
private static String genderText ( Integer gender ) {
if ( gender = = null ) {
return null ;
}
switch ( gender ) {
case 0 : return " 男卫 " ;
case 1 : return " 女卫 " ;
case 2 : return " 母婴 " ;
case 3 : return " 残卫 " ;
case 4 : return " 第三 " ;
case 5 : return " 其他 " ;
default : return null ;
}
}
private record GroupKey ( String date , String locationType , Long locationId , Long toiletId ) {
}
private static final class Aggregate {
long paperLengthCm ;
long useCount ;
Integer gender ;
final Set < String > snCodes = new TreeSet < > ( ) ;
}
}