From 1f145e0c57008dc5da2a1c88027de371fde6768b Mon Sep 17 00:00:00 2001 From: wangheng Date: Thu, 24 Sep 2026 09:40:06 +0800 Subject: [PATCH] =?UTF-8?q?feat(mcp):=20=E6=96=B0=E5=A2=9E=E8=AE=BE?= =?UTF-8?q?=E5=A4=87=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - hardware.device.lifecycle.query:按 SN 模糊分页查询 device_life_cycle 当前状态, 含流转/在途/在库/联网/资产五组状态文案、关键日期、在途天数与超期标记 (阈值取 Redis Dictionary.MaxRoadDays,缺失 fail fast) - hardware.device.lifecycle.detail.query:按 SN 精确聚合事件时间线, 覆盖生产档案/质检/出入库(含发货信息)/安装上下线/备用机日志(ES hardwarelog), 时间倒序,SN 不存在返回 found=false - 复刻老系统 lifeCycleListByPage 与 lookDetail,按拍板不做权限校验、 不复制 exchange_state 排除、物流公司名用 mall_order_logistics 冗余列 - ES 备用机日志走低阶 RestClient 云集群,SpecialSncode 集合命中跳过 - 新增 15 个单测(含 ES 请求体断言、排序、null 安全、fail fast 路径) - 设计文档:doc/device-lifecycle-mcp-tool-design.md --- .../doc/device-lifecycle-mcp-tool-design.md | 168 ++++++ .../iiv/agent/entity/m0/DeviceLifeCycle.java | 63 ++ .../java/me/iiv/agent/entity/m0/District.java | 25 + .../agent/entity/m0/HardwareCheckRecord.java | 29 + .../agent/entity/m0/HardwareInstallLog.java | 37 ++ .../iiv/agent/entity/m0/HardwareSncode.java | 43 ++ .../me/iiv/agent/entity/m2/Warehouse.java | 26 + .../agent/entity/m2/WarehouseInDetails.java | 38 ++ .../agent/entity/m2/WarehouseOutDetails.java | 40 ++ .../me/iiv/agent/es/HardwareLogEsGateway.java | 64 ++ .../agent/es/HardwareLogEsGatewayImpl.java | 114 ++++ .../mapper/m0/DeviceLifeCycleMapper.java | 7 + .../iiv/agent/mapper/m0/DistrictMapper.java | 7 + .../mapper/m0/HardwareCheckRecordMapper.java | 7 + .../mapper/m0/HardwareInstallLogMapper.java | 7 + .../agent/mapper/m0/HardwareSncodeMapper.java | 7 + .../mapper/m2/WarehouseInDetailsMapper.java | 7 + .../iiv/agent/mapper/m2/WarehouseMapper.java | 7 + .../mapper/m2/WarehouseOutDetailsMapper.java | 7 + .../agent/mcp/tool/DeviceLifecycleTools.java | 555 ++++++++++++++++++ .../es/HardwareLogEsGatewayImplTest.java | 112 ++++ .../mcp/tool/DeviceLifecycleToolsTest.java | 473 +++++++++++++++ 22 files changed, 1843 insertions(+) create mode 100644 xiaoqu-agent-service/doc/device-lifecycle-mcp-tool-design.md create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/DeviceLifeCycle.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/District.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/HardwareCheckRecord.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/HardwareInstallLog.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/HardwareSncode.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m2/Warehouse.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m2/WarehouseInDetails.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m2/WarehouseOutDetails.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/es/HardwareLogEsGateway.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/es/HardwareLogEsGatewayImpl.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/DeviceLifeCycleMapper.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/DistrictMapper.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/HardwareCheckRecordMapper.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/HardwareInstallLogMapper.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/HardwareSncodeMapper.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m2/WarehouseInDetailsMapper.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m2/WarehouseMapper.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m2/WarehouseOutDetailsMapper.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/mcp/tool/DeviceLifecycleTools.java create mode 100644 xiaoqu-agent-service/src/test/java/me/iiv/agent/es/HardwareLogEsGatewayImplTest.java create mode 100644 xiaoqu-agent-service/src/test/java/me/iiv/agent/mcp/tool/DeviceLifecycleToolsTest.java diff --git a/xiaoqu-agent-service/doc/device-lifecycle-mcp-tool-design.md b/xiaoqu-agent-service/doc/device-lifecycle-mcp-tool-design.md new file mode 100644 index 0000000..b670f6f --- /dev/null +++ b/xiaoqu-agent-service/doc/device-lifecycle-mcp-tool-design.md @@ -0,0 +1,168 @@ +# 设备生命周期查询 MCP 工具设计 + +需求:设备生命周期按 SN 查询(列表 + 详情两个工具),2026-09-23 用户拍板「按建议来」 + +工具一:`hardware.device.lifecycle.query`(当前状态,列表) +工具二:`hardware.device.lifecycle.detail.query`(事件时间线,详情) + +## 背景 + +老系统 `LifeCycleController.lifeCycleListByPage`(xiaoqu-franchisee :63-161)分页查询 +`device_life_cycle` 表(**m0 库**,mapper 在 `mapper.m0`,与 battery_fault_log 同库), +实体 `beans.b0.DeviceLifeCycle`(xiaoqu-publicbeanandmap)。 + +表字段(23 个业务字段): + +- 标识:`sn_code`、`device_type`(0出纸机/1空感/2电池/3充电箱/4泡沫机/5蓝牙网关) +- 状态组:`exchange_state`(0未生产/1生产中/2生产完成/3出厂/4报废/5自用/6出库/7入库/8安装/9上线/10下线/11备用/12解除备用/13重工)、 + `up_exchange_state`(上次流转状态)、`road_state`(-1初始化/0落地/1在途)、 + `inventory_state`(-1初始化/0非在库/1在库)、`network_state`(0离线/1在线)、 + `asset_state`(0库存商品/1固定资产/2出租/3售出/4报废/5费用化) +- 日期组:`producing_date`、`produce_finish_date`、`ex_factory_date`、`first_use_date`、 + `discard_date`、`again_produce_date`、`road_date`(在途开始时间)、`last_online_date` +- 归属:`agent_id`/`agent_name`(资产使用公司)、`asset_owner_id`/`asset_owner_name`(资产所属公司)、`destination`(去向) +- 其他:`last_op_user`/`last_op_date`(最近流转人与时间)、`last_latitude_and_longitude`(最近经纬度)、 + `jindie_sync_state`/`jindie_internal_id`(金蝶同步) + +老接口的行为与坑: + +1. **行级权限**:按 `isagent` + agentId 过滤行(本次用户拍板:不做权限,都可以查)。 +2. **字段级权限**:`FieldWebpageAuthority` 按用户角色动态裁剪返回列(MCP 场景无此概念,不复制)。 +3. **写死排除 `exchange_state ∈ (0,1)`**:列表里永远看不到"未生产/生产中"的设备。 + 按 SN 查设备的场景下这个排除会把新投产设备查成"不存在",**不建议复制**(见决策表)。 +4. **在途时长是计算字段**:`roadState=1 && roadDate!=null` 时 roadDays = roadDate 到今天的自然日数; + 超过 Redis `Dictionary.MaxRoadDays` 时 roadDaysFlag=1(列表标红用)。 +5. 多类型日期区间、在途天数区间等筛选项是为列表页设计的,按 SN 查询用不上,不复制。 +6. `WrapperUtils.beanToWrapper` 对字符串列是 like 模糊匹配(snCode 实际为模糊查询)。 + +## 设计决策(用户已拍板 2026-09-23) + +| # | 决策 | 说明 | +|---|---|---| +| 1 | 不做任何权限校验 | 用户拍板:都可以查;访问控制由 MCP ak/scope 层兜底(与 electricity.message 一致) | +| 2 | 不复制 exchange_state 排除 | 老系统写死排除未生产/生产中,按 SN 精确查会误报"不存在";新工具全状态可见。**若要严格对齐老列表口径请告知** | +| 3 | snCode 模糊匹配 | 对齐老系统 like 语义:传完整 SN 返回唯一一条;传片段返回多条分页列表 | +| 4 | 保留在途时长计算 | roadDays / roadDaysFlag 是老列表的核心展示字段,服务端算好返回;Redis `Dictionary.MaxRoadDays` 缺失时 fail fast(与 paper 系列工具一致) | +| 5 | 枚举全部配文案映射 | deviceType/exchangeState/roadState/inventoryState/networkState/assetState/jindieSyncState 各配 `*Text` 字段,LLM 友好 | +| 6 | 金蝶字段原样返回 | jindieSyncState/jindieInternalId 保留,排查资产同步问题时有用 | + +## 参数契约 + +- `snCode`:String,必填非空;like 模糊匹配(对齐老系统),命中唯一即单设备详情语义。 +- `page`:Integer,默认 1(<1 归一为 1)。 +- `rows`:Integer,默认 20、上限 100;>100 截断为 100 并在 notice 提示(与项目现有工具惯例一致)。 + +固定条件:`soft_delete=0`,按 `id ASC` 稳定排序(对齐老系统)。 + +## 返回契约 + +``` +total / page / rows / notice? / records[] +record: + snCode / deviceType / deviceTypeText + exchangeState / exchangeStateText / upExchangeState / upExchangeStateText + roadState / roadStateText / roadDate / roadDays / roadDaysFlag + inventoryState / inventoryStateText / networkState / networkStateText + assetState / assetStateText + destination / agentId / agentName / assetOwnerId / assetOwnerName + producingDate / produceFinishDate / exFactoryDate / firstUseDate / discardDate / againProduceDate + lastOpUser / lastOpDate / lastOnlineDate / lastLatitudeAndLongitude + jindieSyncState / jindieSyncStateText / jindieInternalId + createTime / modifyTime +``` + +- 所有日期:`yyyy-MM-dd HH:mm:ss`(Asia/Shanghai),null 原样为 null。 +- `roadDays`:仅 `roadState=1 && roadDate!=null` 时返回自然日数,否则 null;`roadDaysFlag` 默认 0, + roadDays > `MaxRoadDays` 时为 1。 +- 枚举值遇到未知 code:`*Text` 返回 `未知(code)`,原 code 照常返回(与 device_average 工具一致)。 +- `upExchangeState` 为 null 时 `upExchangeStateText` 为 null。 + +## 代码结构 + +- `entity/m0/DeviceLifeCycle`:MyBatis-Plus 实体,映射 `device_life_cycle` 全字段。 +- `mapper/m0/DeviceLifeCycleMapper`:BaseMapper,无需自定义 SQL(条件简单,LambdaQueryWrapper 即可)。 +- `mcp/tool/DeviceLifecycleTools`:`@XqTool(category="hardware", kind="read")` + + `@Tool(name="hardware.device.lifecycle.query")`;参数校验、枚举文案映射、在途时长计算、notice 拼接。 + +无权限校验、无 ES、无跨库 join,单表分页查询。 + +## 验证 + +- `DeviceLifecycleToolsTest`(mock Mapper):空 snCode 拒绝且零 Mapper 交互;rows 上限截断 notice; + soft_delete/id ASC 条件透传;枚举文案映射(含未知 code 与 null);roadDays/roadDaysFlag 计算 + (在途未超期/超期/非在途三种);MaxRoadDays 字典缺失 fail fast;返回字段完整性;Spring AI schema。 +- 全量 Maven 测试确认无回归。 + +## 工具二:hardware.device.lifecycle.detail.query(详情时间线) + +老系统 `AssetDepreciationSetController.lookDetail`(xiaoqu-franchisee :141-418)按 SN 聚合 6 个数据源, +返回按操作时间倒序的生命周期事件列表(`AssetDetailsOutput`:title + 中文标签 LinkedHashMap)。 + +### 事件来源(全部 soft_delete=0) + +| 事件 type | 标题 | 来源 | 库 | 时间字段 | 字段 | +|---|---|---|---|---|---| +| unproduced | 未生产 | hardware_sncode.create_time | m0 | createTime | orderNo/orderPack/materialNo/materielFullName/nfcBound/sysversion/hardVersion/memo/operator | +| producing | 生产中 | hardware_sncode.unbing_time(null 则不产生) | m0 | unbingTime | operator | +| produced | 生产完成 | hardware_check_record limit 1 | m0 | modifyTime | operator | +| inbound | 入库 | warehouse_in_details(order_state=3) | m2 | inConfirmTime | inOrderNo/warehouseTypeName/applyUserName/applyTime/warehouseName/inConfirmUserName/inDate | +| rework | 重工 | 同上,仓库号=1000000998 | m2 | 同上 | 同上 | +| outbound | 出库 | warehouse_out_details(order_state=3) | m2 | outConfirmTime | outOrderNo/warehouseTypeName/applyUserName/applyTime/warehouseName/useCustomerName/outConfirmUserName/outDate + shipping | +| exFactory | 出厂 | 同上,仓库号=BJ001 | m2 | 同上 | 同上 | +| install | 安装 | hardware_install_log(logType=0) | m0 | onlineTime | agentName/propertyName/districtName/address/operator | +| online | 上线 | 同上(logType=1) | m0 | 同上 | 同上 | +| offline | 下线 | 同上(logType=2) | m0 | 同上 | 同上 | +| backup | 备用 | ES hardwarelog(term snCode + term logType=备用机操作日志,id DESC,size 1000) | 云集群 | createTime | agentName/propertyName/districtName/event/operator(userName) | + +发货信息 shipping(出库/出厂事件内嵌):优先 mall_order_no、否则 out_order_no 查 +m1 `mall_order_logistics`(soft_delete=0);sendMode=0 → {mode:"快递", logisticsName, logisticsOrderNo}, +sendMode=1 → {mode:"自行派送", deliverName},其余/查不到不返回 shipping。 +物流公司名直接用 mall_order_logistics.logistics_name 冗余列,不再 join mall_logistics(刻意的简化)。 + +### 老接口的坑与对策 + +1. 权限:仅代理角色 + 按公司过滤 → 按拍板不做权限。 +2. SN 不在 hardware_sncode → 老接口报错「设备编号不正确」;新工具返回 `found=false, events=[]` + notice。 +3. 老代码多处 NPE(名称解析不判空、sendMode null 拆箱)→ 全部 null 安全,查不到为 null。 +4. 备用机日志 ES 异常被 catch 吞掉 → fail fast 抛 IllegalStateException(项目惯例)。 +5. SN 在 Redis 集合 `SpecialSncode` 中跳过备用机日志查询(对齐老系统)。 +6. 发货图片 OSS 列表不返回(对 LLM 无用,刻意差异)。 +7. 老系统标题「生成完成」为笔误,改为「生产完成」。 +8. 老排序 comparator 对相等时间违反契约 → 新排序 time DESC、null 排最后,稳定排序。 +9. 老代码逐条 selectById 解析名称(N+1)→ 批量收集 id 后 selectBatchIds 一次解析。 + +### 参数契约 + +- `snCode`:String,必填非空,自动 trim;精确匹配(详情语义就是单台设备)。 + +### 返回契约 + +``` +snCode / found / notice? / total / events[] +event: type / title / time / fields{...} +``` + +- `time`:yyyy-MM-dd HH:mm:ss(Asia/Shanghai);入库/出库的 inDate/outDate 为 yyyy-MM-dd。 +- `events` 按 time 倒序,null 时间排最后。 + +## 代码结构 + +- `entity/m0`:DeviceLifeCycle、HardwareSncode、HardwareInstallLog、HardwareCheckRecord、District(仅 id/districtName) +- `mapper/m0`:对应 5 个 BaseMapper +- `entity/m2`:WarehouseInDetails、WarehouseOutDetails、Warehouse(仅 id/warehouseNo) +- `mapper/m2`:对应 3 个 BaseMapper +- `es/HardwareLogEsGateway(+Impl)`:备用机日志查询,只注入 `esCloudRestClient` 低阶客户端 + (生产 ES 7.7.1 与高阶客户端不兼容,见 EsClientConfig 注释);ES 异常抛 IllegalStateException +- `mcp/tool/DeviceLifecycleTools`:两个 @Tool 方法,参数校验、枚举文案映射、在途时长计算、 + 事件聚合与名称批量解析、notice 拼接 + +## 验证 + +- `DeviceLifecycleToolsTest`(mock 各 Mapper + Gateway + Redis): + 列表——空 snCode 拒绝、rows 截断 notice、枚举映射、roadDays/roadDaysFlag、MaxRoadDays 缺失 fail fast; + 详情——SN 不存在返回 found=false、各事件类型聚合与字段映射、出厂/重工仓库号特判、 + 发货信息两种 sendMode、SpecialSncode 跳过 ES、名称解析 null 安全、时间倒序、Spring AI schema。 +- `HardwareLogEsGatewayImplTest`(mock RestClient):term 过滤、id DESC、size 1000、 + createTime epoch 毫秒归一、ES 异常包装。 +- 全量 Maven 测试确认无回归。 + diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/DeviceLifeCycle.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/DeviceLifeCycle.java new file mode 100644 index 0000000..61bc111 --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/DeviceLifeCycle.java @@ -0,0 +1,63 @@ +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.device_life_cycle)。 */ +@Getter +@Setter +@ToString +@TableName("device_life_cycle") +public class DeviceLifeCycle 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; + /** 设备类型(0:出纸机;1:空感;2:电池;3:充电箱;4:泡沫机;5:蓝牙网关) */ + private Integer deviceType; + private String snCode; + /** 当前流转状态(0:未生产;1:生产中;2:生产完成;3:出厂;4:报废;5:自用;6:出库;7:入库;8:安装;9:上线;10:下线;11:备用;12:解除备用;13:重工) */ + private Integer exchangeState; + private Integer upExchangeState; + /** 途径状态(-1:初始化;0:落地;1:在途) */ + private Integer roadState; + /** 在库状态(-1:初始化;0:非在库;1:在库) */ + private Integer inventoryState; + /** 联网状态(0:离线;1:在线) */ + private Integer networkState; + private String destination; + private Date producingDate; + private Date produceFinishDate; + private Date exFactoryDate; + private Date firstUseDate; + private Date discardDate; + private Date againProduceDate; + private String lastOpUser; + private Date lastOpDate; + /** 在途开始时间 */ + private Date roadDate; + private Date lastOnlineDate; + private String lastLatitudeAndLongitude; + /** 资产属性(0:库存商品;1:固定资产;2:出租;3:售出;4:报废;5:费用化) */ + private Integer assetState; + private Long agentId; + private String agentName; + private Long assetOwnerId; + private String assetOwnerName; + /** 金蝶同步状态(0:未同步;1:已同步) */ + private Integer jindieSyncState; + private String jindieInternalId; +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/District.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/District.java new file mode 100644 index 0000000..8dd22d1 --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/District.java @@ -0,0 +1,25 @@ +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; + +/** 站点(m0.district),生命周期详情只取名称。 */ +@Getter +@Setter +@ToString +@TableName("district") +public class District implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + private Integer softDelete; + private String districtName; +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/HardwareCheckRecord.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/HardwareCheckRecord.java new file mode 100644 index 0000000..4ec90eb --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/HardwareCheckRecord.java @@ -0,0 +1,29 @@ +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.hardware_check_record),生命周期详情的"生产完成"事件来源。 */ +@Getter +@Setter +@ToString +@TableName("hardware_check_record") +public class HardwareCheckRecord implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + private Long createId; + private Date createTime; + private Date modifyTime; + private Integer softDelete; + private String snCode; +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/HardwareInstallLog.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/HardwareInstallLog.java new file mode 100644 index 0000000..32a540c --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/HardwareInstallLog.java @@ -0,0 +1,37 @@ +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.hardware_install_log)。 */ +@Getter +@Setter +@ToString +@TableName("hardware_install_log") +public class HardwareInstallLog implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + private Long createId; + private Date createTime; + private Integer softDelete; + private String snCode; + private String address; + private Long districtId; + private Long propertyId; + private Long agentId; + /** 安装/上线/下线发生时间 */ + private Date onlineTime; + /** 0:安装;1:上线;2:下线 */ + private Integer logType; + private Integer deviceType; +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/HardwareSncode.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/HardwareSncode.java new file mode 100644 index 0000000..19472ac --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m0/HardwareSncode.java @@ -0,0 +1,43 @@ +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; + +/** 设备 SN 生产档案(m0.hardware_sncode),生命周期详情的生产侧事件来源。 */ +@Getter +@Setter +@ToString +@TableName("hardware_sncode") +public class HardwareSncode 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 String orderNo; + /** 生产批次号 */ + private String orderPack; + /** 解绑时间,老系统以此作为"生产中"事件时间 */ + private Date unbingTime; + private String sysversion; + private String materialNo; + private String materielFullName; + /** 是否绑定 NFC(0:否;1:是) */ + private Integer nfcFlag; + private String hardVersion; + private String memo; +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m2/Warehouse.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m2/Warehouse.java new file mode 100644 index 0000000..a74432e --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m2/Warehouse.java @@ -0,0 +1,26 @@ +package me.iiv.agent.entity.m2; + +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; + +/** 仓库(m2.warehouse),生命周期详情只取仓库号做特判(BJ001=出厂仓、1000000998=重工仓)。 */ +@Getter +@Setter +@ToString +@TableName("warehouse") +public class Warehouse implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + private Integer softDelete; + private String warehouseNo; + private String warehouseName; +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m2/WarehouseInDetails.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m2/WarehouseInDetails.java new file mode 100644 index 0000000..03b6ff2 --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m2/WarehouseInDetails.java @@ -0,0 +1,38 @@ +package me.iiv.agent.entity.m2; + +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.time.LocalDate; +import java.util.Date; + +/** 入库单明细(m2.warehouse_in_details),生命周期详情的入库/重工事件来源。 */ +@Getter +@Setter +@ToString +@TableName("warehouse_in_details") +public class WarehouseInDetails implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + private Date createTime; + private Integer softDelete; + private String snCode; + private String inOrderNo; + private Long warehouseId; + private String warehouseName; + private String warehouseTypeName; + /** 单据状态,生命周期只取 3=已确认 */ + private Integer orderState; + private String applyUserName; + private String inConfirmUserName; + private Date inConfirmTime; + private LocalDate inDate; +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m2/WarehouseOutDetails.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m2/WarehouseOutDetails.java new file mode 100644 index 0000000..81bb932 --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/entity/m2/WarehouseOutDetails.java @@ -0,0 +1,40 @@ +package me.iiv.agent.entity.m2; + +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.time.LocalDate; +import java.util.Date; + +/** 出库单明细(m2.warehouse_out_details),生命周期详情的出库/出厂事件来源。 */ +@Getter +@Setter +@ToString +@TableName("warehouse_out_details") +public class WarehouseOutDetails implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + private Date createTime; + private Integer softDelete; + private String snCode; + private String outOrderNo; + private String mallOrderNo; + private Long warehouseId; + private String warehouseName; + private String warehouseTypeName; + /** 单据状态,生命周期只取 3=已确认 */ + private Integer orderState; + private String applyUserName; + private String outConfirmUserName; + private Date outConfirmTime; + private LocalDate outDate; + private String useCustomerName; +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/es/HardwareLogEsGateway.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/es/HardwareLogEsGateway.java new file mode 100644 index 0000000..a46a8cf --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/es/HardwareLogEsGateway.java @@ -0,0 +1,64 @@ +package me.iiv.agent.es; + +import java.util.List; + +/** + * hardwarelog(设备操作日志)ES 查询网关。 + * 只走云 ES 集群(老系统 BaseSearchSupportImpl 注入主集群 restClient, + * 即 es_hosts 集群),索引固定 hardwarelog,便于单测 mock。 + */ +public interface HardwareLogEsGateway { + + /** + * 查询单台设备的备用机操作日志(logType=备用机操作日志)。 + * + * @param snCode 设备 SN,term 精确匹配 + * @param size 返回上限(老系统固定 1000) + * @return 命中记录,按 id DESC + */ + List findBackupLogs(String snCode, int size); + + /** 单条备用机日志(createTime 已统一为 yyyy-MM-dd HH:mm:ss 文本,Asia/Shanghai)。 */ + class Record { + private final String createTime; + private final String event; + private final String userName; + private final Long agentId; + private final Long propertyId; + private final Long districtId; + + public Record(String createTime, String event, String userName, + Long agentId, Long propertyId, Long districtId) { + this.createTime = createTime; + this.event = event; + this.userName = userName; + this.agentId = agentId; + this.propertyId = propertyId; + this.districtId = districtId; + } + + public String getCreateTime() { + return createTime; + } + + public String getEvent() { + return event; + } + + public String getUserName() { + return userName; + } + + public Long getAgentId() { + return agentId; + } + + public Long getPropertyId() { + return propertyId; + } + + public Long getDistrictId() { + return districtId; + } + } +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/es/HardwareLogEsGatewayImpl.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/es/HardwareLogEsGatewayImpl.java new file mode 100644 index 0000000..d184aea --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/es/HardwareLogEsGatewayImpl.java @@ -0,0 +1,114 @@ +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.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +/** + * hardwarelog ES 查询实现(备用机操作日志)。 + * 只注入 esCloudRestClient 低阶客户端:老系统 BaseSearchSupportImpl 用的主集群 + * (es_hosts,即本服务的 cloud 集群);生产 ES 7.7.1 与高阶客户端不兼容 + * (vendor Content-Type 406 + X-Elastic-Product 校验,见 EsClientConfig 注释)。 + * 查询口径对齐老 AssetDepreciationSetController.lookDetail 的备用机日志段: + * term snCode + term logType=备用机操作日志,id DESC,size 上限 1000。 + * ES 异常不静默(老系统 printStackTrace 吞掉),抛 IllegalStateException。 + */ +@Component +public class HardwareLogEsGatewayImpl implements HardwareLogEsGateway { + + private static final String INDEX = "hardwarelog"; + private static final String BACKUP_LOG_TYPE = "备用机操作日志"; + private static final DateTimeFormatter TIME_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai")); + + private final RestClient cloudRestClient; + private final ObjectMapper mapper = new ObjectMapper(); + + public HardwareLogEsGatewayImpl(@Qualifier("esCloudRestClient") RestClient cloudRestClient) { + this.cloudRestClient = cloudRestClient; + } + + @Override + public List findBackupLogs(String snCode, int size) { + try { + ObjectNode body = mapper.createObjectNode(); + body.put("size", size); + body.put("track_total_hits", false); + body.putArray("sort").addObject().putObject("id").put("order", "desc"); + ObjectNode bool = body.putObject("query").putObject("bool"); + ArrayNode filters = bool.putArray("filter"); + filters.addObject().putObject("term").put("snCode", snCode); + filters.addObject().putObject("term").put("logType", BACKUP_LOG_TYPE); + + Request req = new Request("POST", "/" + INDEX + "/_search"); + req.setJsonEntity(mapper.writeValueAsString(body)); + Response resp = cloudRestClient.performRequest(req); + JsonNode root = mapper.readTree(resp.getEntity().getContent()); + + List records = new ArrayList<>(); + for (JsonNode hit : root.path("hits").path("hits")) { + JsonNode source = hit.path("_source"); + records.add(new Record( + normalizeTime(source.get("createTime")), + textOrNull(source.get("event")), + textOrNull(source.get("userName")), + longOrNull(source.get("agentId")), + longOrNull(source.get("propertyId")), + longOrNull(source.get("districtId")))); + } + return records; + } catch (IOException | RuntimeException e) { + throw new IllegalStateException("ES 查询备用机操作日志失败: " + e.getMessage(), e); + } + } + + /** createTime 兼容 epoch 毫秒与文本两种存储形态,统一归一为 Asia/Shanghai 文本。 */ + private static String normalizeTime(JsonNode node) { + if (node == null || node.isNull()) { + return null; + } + if (node.isNumber()) { + return TIME_FORMATTER.format(Instant.ofEpochMilli(node.asLong())); + } + String text = node.asText(null); + if (text == null) { + return null; + } + try { + return TIME_FORMATTER.format(Instant.ofEpochMilli(Long.parseLong(text.trim()))); + } catch (NumberFormatException ignored) { + return text; + } + } + + private static String textOrNull(JsonNode node) { + return node == null || node.isNull() ? null : node.asText(); + } + + private static Long longOrNull(JsonNode node) { + if (node == null || node.isNull()) { + return null; + } + if (node.isNumber()) { + return node.asLong(); + } + try { + return Long.parseLong(node.asText().trim()); + } catch (NumberFormatException ignored) { + return null; + } + } +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/DeviceLifeCycleMapper.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/DeviceLifeCycleMapper.java new file mode 100644 index 0000000..88ba899 --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/DeviceLifeCycleMapper.java @@ -0,0 +1,7 @@ +package me.iiv.agent.mapper.m0; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import me.iiv.agent.entity.m0.DeviceLifeCycle; + +public interface DeviceLifeCycleMapper extends BaseMapper { +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/DistrictMapper.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/DistrictMapper.java new file mode 100644 index 0000000..084c238 --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/DistrictMapper.java @@ -0,0 +1,7 @@ +package me.iiv.agent.mapper.m0; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import me.iiv.agent.entity.m0.District; + +public interface DistrictMapper extends BaseMapper { +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/HardwareCheckRecordMapper.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/HardwareCheckRecordMapper.java new file mode 100644 index 0000000..c6098e7 --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/HardwareCheckRecordMapper.java @@ -0,0 +1,7 @@ +package me.iiv.agent.mapper.m0; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import me.iiv.agent.entity.m0.HardwareCheckRecord; + +public interface HardwareCheckRecordMapper extends BaseMapper { +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/HardwareInstallLogMapper.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/HardwareInstallLogMapper.java new file mode 100644 index 0000000..9243902 --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/HardwareInstallLogMapper.java @@ -0,0 +1,7 @@ +package me.iiv.agent.mapper.m0; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import me.iiv.agent.entity.m0.HardwareInstallLog; + +public interface HardwareInstallLogMapper extends BaseMapper { +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/HardwareSncodeMapper.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/HardwareSncodeMapper.java new file mode 100644 index 0000000..4dd1548 --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m0/HardwareSncodeMapper.java @@ -0,0 +1,7 @@ +package me.iiv.agent.mapper.m0; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import me.iiv.agent.entity.m0.HardwareSncode; + +public interface HardwareSncodeMapper extends BaseMapper { +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m2/WarehouseInDetailsMapper.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m2/WarehouseInDetailsMapper.java new file mode 100644 index 0000000..a67ebef --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m2/WarehouseInDetailsMapper.java @@ -0,0 +1,7 @@ +package me.iiv.agent.mapper.m2; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import me.iiv.agent.entity.m2.WarehouseInDetails; + +public interface WarehouseInDetailsMapper extends BaseMapper { +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m2/WarehouseMapper.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m2/WarehouseMapper.java new file mode 100644 index 0000000..c39b2b2 --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m2/WarehouseMapper.java @@ -0,0 +1,7 @@ +package me.iiv.agent.mapper.m2; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import me.iiv.agent.entity.m2.Warehouse; + +public interface WarehouseMapper extends BaseMapper { +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m2/WarehouseOutDetailsMapper.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m2/WarehouseOutDetailsMapper.java new file mode 100644 index 0000000..ea72fea --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mapper/m2/WarehouseOutDetailsMapper.java @@ -0,0 +1,7 @@ +package me.iiv.agent.mapper.m2; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import me.iiv.agent.entity.m2.WarehouseOutDetails; + +public interface WarehouseOutDetailsMapper extends BaseMapper { +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/mcp/tool/DeviceLifecycleTools.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mcp/tool/DeviceLifecycleTools.java new file mode 100644 index 0000000..fcd9c72 --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mcp/tool/DeviceLifecycleTools.java @@ -0,0 +1,555 @@ +package me.iiv.agent.mcp.tool; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import me.iiv.agent.entity.m0.Agent; +import me.iiv.agent.entity.m0.DeviceLifeCycle; +import me.iiv.agent.entity.m0.District; +import me.iiv.agent.entity.m0.HardwareCheckRecord; +import me.iiv.agent.entity.m0.HardwareInstallLog; +import me.iiv.agent.entity.m0.HardwareSncode; +import me.iiv.agent.entity.m0.Properyt; +import me.iiv.agent.entity.m0.User; +import me.iiv.agent.entity.m1.MallOrderLogistics; +import me.iiv.agent.entity.m2.Warehouse; +import me.iiv.agent.entity.m2.WarehouseInDetails; +import me.iiv.agent.entity.m2.WarehouseOutDetails; +import me.iiv.agent.es.HardwareLogEsGateway; +import me.iiv.agent.mapper.m0.AgentMapper; +import me.iiv.agent.mapper.m0.DeviceLifeCycleMapper; +import me.iiv.agent.mapper.m0.DistrictMapper; +import me.iiv.agent.mapper.m0.HardwareCheckRecordMapper; +import me.iiv.agent.mapper.m0.HardwareInstallLogMapper; +import me.iiv.agent.mapper.m0.HardwareSncodeMapper; +import me.iiv.agent.mapper.m0.ProperytMapper; +import me.iiv.agent.mapper.m0.UserMapper; +import me.iiv.agent.mapper.m1.MallOrderLogisticsMapper; +import me.iiv.agent.mapper.m2.WarehouseInDetailsMapper; +import me.iiv.agent.mapper.m2.WarehouseMapper; +import me.iiv.agent.mapper.m2.WarehouseOutDetailsMapper; +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.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * 设备生命周期查询工具(按 SN),复刻老系统两个入口: + * 列表 lifeCycle/lifeCycleListByPage(device_life_cycle 当前状态) + * 与详情 assetDepreciationSet/lookDetail(多源聚合事件时间线)。 + * 按用户拍板:不做任何权限校验(老系统列表有行/字段权限、详情有代理角色限制,均不复制)。 + * 与老系统的差异详见 doc/device-lifecycle-mcp-tool-design.md。 + */ +@Component +public class DeviceLifecycleTools implements ToolObject { + + private static final int DEFAULT_ROWS = 20; + private static final int MAX_ROWS = 100; + private static final int BACKUP_LOG_SIZE = 1000; + 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 static final DateTimeFormatter PARSE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + /** 出厂仓(出库事件标题改为"出厂")、重工仓(入库事件标题改为"重工"),与老系统一致 */ + private static final String EX_FACTORY_WAREHOUSE_NO = "BJ001"; + private static final String REWORK_WAREHOUSE_NO = "1000000998"; + private static final String SPECIAL_SNCODE_SET = "SpecialSncode"; + + final DeviceLifeCycleMapper deviceLifeCycleMapper; + final HardwareSncodeMapper hardwareSncodeMapper; + final HardwareCheckRecordMapper hardwareCheckRecordMapper; + final HardwareInstallLogMapper hardwareInstallLogMapper; + final WarehouseInDetailsMapper warehouseInDetailsMapper; + final WarehouseOutDetailsMapper warehouseOutDetailsMapper; + final WarehouseMapper warehouseMapper; + final MallOrderLogisticsMapper mallOrderLogisticsMapper; + final AgentMapper agentMapper; + final ProperytMapper properytMapper; + final DistrictMapper districtMapper; + final UserMapper userMapper; + final HardwareLogEsGateway hardwareLogEsGateway; + final StringRedisTemplate redisTemplate; + + public DeviceLifecycleTools(DeviceLifeCycleMapper deviceLifeCycleMapper, + HardwareSncodeMapper hardwareSncodeMapper, + HardwareCheckRecordMapper hardwareCheckRecordMapper, + HardwareInstallLogMapper hardwareInstallLogMapper, + WarehouseInDetailsMapper warehouseInDetailsMapper, + WarehouseOutDetailsMapper warehouseOutDetailsMapper, + WarehouseMapper warehouseMapper, + MallOrderLogisticsMapper mallOrderLogisticsMapper, + AgentMapper agentMapper, + ProperytMapper properytMapper, + DistrictMapper districtMapper, + UserMapper userMapper, + HardwareLogEsGateway hardwareLogEsGateway, + StringRedisTemplate redisTemplate) { + this.deviceLifeCycleMapper = deviceLifeCycleMapper; + this.hardwareSncodeMapper = hardwareSncodeMapper; + this.hardwareCheckRecordMapper = hardwareCheckRecordMapper; + this.hardwareInstallLogMapper = hardwareInstallLogMapper; + this.warehouseInDetailsMapper = warehouseInDetailsMapper; + this.warehouseOutDetailsMapper = warehouseOutDetailsMapper; + this.warehouseMapper = warehouseMapper; + this.mallOrderLogisticsMapper = mallOrderLogisticsMapper; + this.agentMapper = agentMapper; + this.properytMapper = properytMapper; + this.districtMapper = districtMapper; + this.userMapper = userMapper; + this.hardwareLogEsGateway = hardwareLogEsGateway; + this.redisTemplate = redisTemplate; + } + + // ---------- 工具一:当前状态列表 ---------- + + @XqTool(category = "hardware", kind = "read") + @Tool(name = "hardware.device.lifecycle.query", description = "按 SN 查询设备生命周期当前状态" + + "(m0 device_life_cycle,复刻老系统 /lifeCycle/lifeCycleListByPage,无权限过滤)。" + + "snCode 必填,模糊匹配:传完整 SN 返回唯一一条,传片段返回多条分页列表;" + + "返回流转/在途/在库/联网/资产五组状态(含中文文案)、生产/出厂/首用/报废/重工日期、" + + "归属公司、最近流转人与时间、最近在线时间与经纬度、金蝶同步状态;" + + "在途设备另返回在途天数 roadDays 与超期标记 roadDaysFlag(阈值取 Redis Dictionary.MaxRoadDays)。" + + "page 默认 1、rows 默认 20、上限 100。") + public Map hardwareDeviceLifecycleQuery( + @ToolParam(description = "设备 SN,必填,非空,模糊匹配") String snCode, + @ToolParam(required = false, description = "页码,从 1 开始,默认 1") Integer page, + @ToolParam(required = false, description = "每页条数,默认 20,上限 100,超出截断为 100") Integer rows) { + if (!StringUtils.hasText(snCode)) { + throw new IllegalArgumentException("snCode 必填,非空"); + } + 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); + + Page result = deviceLifeCycleMapper.selectPage(new Page<>(pageNo, pageSize), + new LambdaQueryWrapper() + .eq(DeviceLifeCycle::getSoftDelete, 0) + .like(DeviceLifeCycle::getSnCode, snCode.trim()) + .orderByAsc(DeviceLifeCycle::getId)); + + Integer maxRoadDays = null; + List> records = new ArrayList<>(); + for (DeviceLifeCycle cycle : result.getRecords()) { + if (cycle.getRoadState() != null && cycle.getRoadState() == 1 && cycle.getRoadDate() != null + && maxRoadDays == null) { + maxRoadDays = maxRoadDays(); + } + records.add(lifecycleRecord(cycle, maxRoadDays)); + } + + Map output = new LinkedHashMap<>(); + output.put("total", result.getTotal()); + output.put("page", pageNo); + output.put("rows", pageSize); + if (truncatedRows) { + output.put("notice", "rows 超过上限 100,已截断为 100"); + } + output.put("records", records); + return output; + } + + private Map lifecycleRecord(DeviceLifeCycle cycle, Integer maxRoadDays) { + Map row = new LinkedHashMap<>(); + row.put("snCode", cycle.getSnCode()); + row.put("deviceType", cycle.getDeviceType()); + row.put("deviceTypeText", enumText(cycle.getDeviceType(), + "出纸机", "空感", "电池", "充电箱", "泡沫机", "蓝牙网关")); + row.put("exchangeState", cycle.getExchangeState()); + row.put("exchangeStateText", enumText(cycle.getExchangeState(), + "未生产", "生产中", "生产完成", "出厂", "报废", "自用", "出库", "入库", "安装", "上线", "下线", "备用", "解除备用", "重工")); + row.put("upExchangeState", cycle.getUpExchangeState()); + row.put("upExchangeStateText", enumText(cycle.getUpExchangeState(), + "未生产", "生产中", "生产完成", "出厂", "报废", "自用", "出库", "入库", "安装", "上线", "下线", "备用", "解除备用", "重工")); + row.put("roadState", cycle.getRoadState()); + row.put("roadStateText", roadInventoryText(cycle.getRoadState(), "落地", "在途")); + row.put("roadDate", format(cycle.getRoadDate())); + Integer roadDays = null; + Integer roadDaysFlag = 0; + if (cycle.getRoadState() != null && cycle.getRoadState() == 1 && cycle.getRoadDate() != null) { + roadDays = (int) ChronoUnit.DAYS.between( + cycle.getRoadDate().toInstant().atZone(BUSINESS_ZONE).toLocalDate(), LocalDate.now(BUSINESS_ZONE)); + if (maxRoadDays != null && roadDays > maxRoadDays) { + roadDaysFlag = 1; + } + } + row.put("roadDays", roadDays); + row.put("roadDaysFlag", roadDaysFlag); + row.put("inventoryState", cycle.getInventoryState()); + row.put("inventoryStateText", roadInventoryText(cycle.getInventoryState(), "非在库", "在库")); + row.put("networkState", cycle.getNetworkState()); + row.put("networkStateText", enumText(cycle.getNetworkState(), "离线", "在线")); + row.put("assetState", cycle.getAssetState()); + row.put("assetStateText", enumText(cycle.getAssetState(), + "库存商品", "固定资产", "出租", "售出", "报废", "费用化")); + row.put("destination", cycle.getDestination()); + row.put("agentId", cycle.getAgentId()); + row.put("agentName", cycle.getAgentName()); + row.put("assetOwnerId", cycle.getAssetOwnerId()); + row.put("assetOwnerName", cycle.getAssetOwnerName()); + row.put("producingDate", format(cycle.getProducingDate())); + row.put("produceFinishDate", format(cycle.getProduceFinishDate())); + row.put("exFactoryDate", format(cycle.getExFactoryDate())); + row.put("firstUseDate", format(cycle.getFirstUseDate())); + row.put("discardDate", format(cycle.getDiscardDate())); + row.put("againProduceDate", format(cycle.getAgainProduceDate())); + row.put("lastOpUser", cycle.getLastOpUser()); + row.put("lastOpDate", format(cycle.getLastOpDate())); + row.put("lastOnlineDate", format(cycle.getLastOnlineDate())); + row.put("lastLatitudeAndLongitude", cycle.getLastLatitudeAndLongitude()); + row.put("jindieSyncState", cycle.getJindieSyncState()); + row.put("jindieSyncStateText", enumText(cycle.getJindieSyncState(), "未同步", "已同步")); + row.put("jindieInternalId", cycle.getJindieInternalId()); + row.put("createTime", format(cycle.getCreateTime())); + row.put("modifyTime", format(cycle.getModifyTime())); + return row; + } + + /** Redis Dictionary.MaxRoadDays 缺失/非法时 fail fast(与 paper 系列工具口径一致)。 */ + private Integer maxRoadDays() { + Object value = redisTemplate.opsForHash().get("Dictionary", "MaxRoadDays"); + if (value == null) { + throw new IllegalStateException("Redis Dictionary 缺少 MaxRoadDays 字段,无法计算在途超期标记"); + } + try { + return Integer.parseInt(value.toString().trim()); + } catch (NumberFormatException ex) { + throw new IllegalStateException("Redis Dictionary.MaxRoadDays 不是整数: " + value); + } + } + + // ---------- 工具二:事件时间线详情 ---------- + + @XqTool(category = "hardware", kind = "read") + @Tool(name = "hardware.device.lifecycle.detail.query", description = "按 SN 查询设备生命周期事件时间线" + + "(复刻老系统 /assetDepreciationSet/lookDetail,无权限过滤)。snCode 必填精确匹配," + + "聚合生产档案、质检、出入库(含发货信息)、安装/上下线、备用机日志(ES hardwarelog 云集群)" + + "多源事件,按操作时间倒序返回;SN 不存在时返回 found=false 与空事件列表。") + public Map hardwareDeviceLifecycleDetailQuery( + @ToolParam(description = "设备 SN,必填,非空,精确匹配,自动去空格") String snCode) { + if (!StringUtils.hasText(snCode)) { + throw new IllegalArgumentException("snCode 必填,非空"); + } + String sn = snCode.trim(); + + HardwareSncode sncode = hardwareSncodeMapper.selectOne(new LambdaQueryWrapper() + .eq(HardwareSncode::getSoftDelete, 0) + .eq(HardwareSncode::getSncode, sn) + .last("limit 1")); + Map output = new LinkedHashMap<>(); + output.put("snCode", sn); + if (sncode == null) { + output.put("found", false); + output.put("total", 0); + output.put("events", List.of()); + output.put("notice", "hardware_sncode 中不存在该设备编号,未聚合任何事件"); + return output; + } + + List inDetails = warehouseInDetailsMapper.selectList( + new LambdaQueryWrapper() + .eq(WarehouseInDetails::getSoftDelete, 0) + .eq(WarehouseInDetails::getOrderState, 3) + .eq(WarehouseInDetails::getSnCode, sn)); + List outDetails = warehouseOutDetailsMapper.selectList( + new LambdaQueryWrapper() + .eq(WarehouseOutDetails::getSoftDelete, 0) + .eq(WarehouseOutDetails::getOrderState, 3) + .eq(WarehouseOutDetails::getSnCode, sn)); + HardwareCheckRecord checkRecord = hardwareCheckRecordMapper.selectOne( + new LambdaQueryWrapper() + .eq(HardwareCheckRecord::getSoftDelete, 0) + .eq(HardwareCheckRecord::getSnCode, sn) + .last("limit 1")); + List installLogs = hardwareInstallLogMapper.selectList( + new LambdaQueryWrapper() + .eq(HardwareInstallLog::getSoftDelete, 0) + .eq(HardwareInstallLog::getSnCode, sn)); + + // 备用机日志:SN 在 SpecialSncode 集合中跳过(对齐老系统);ES 异常 fail fast + List backupLogs; + Boolean special = redisTemplate.opsForSet().isMember(SPECIAL_SNCODE_SET, sn); + if (Boolean.TRUE.equals(special)) { + backupLogs = List.of(); + } else { + backupLogs = hardwareLogEsGateway.findBackupLogs(sn, BACKUP_LOG_SIZE); + } + + // 批量解析名称,避免老代码逐条 selectById 的 N+1 + Set userIds = new HashSet<>(); + Set agentIds = new HashSet<>(); + Set propertyIds = new HashSet<>(); + Set districtIds = new HashSet<>(); + Set warehouseIds = new HashSet<>(); + addIfNotNull(userIds, sncode.getCreateId(), sncode.getModifyId()); + if (checkRecord != null) { + addIfNotNull(userIds, checkRecord.getCreateId()); + } + for (HardwareInstallLog log : installLogs) { + addIfNotNull(userIds, log.getCreateId()); + addIfNotNull(agentIds, log.getAgentId()); + addIfNotNull(propertyIds, log.getPropertyId()); + addIfNotNull(districtIds, log.getDistrictId()); + } + for (HardwareLogEsGateway.Record log : backupLogs) { + addIfNotNull(agentIds, log.getAgentId()); + addIfNotNull(propertyIds, log.getPropertyId()); + addIfNotNull(districtIds, log.getDistrictId()); + } + for (WarehouseInDetails detail : inDetails) { + addIfNotNull(warehouseIds, detail.getWarehouseId()); + } + for (WarehouseOutDetails detail : outDetails) { + addIfNotNull(warehouseIds, detail.getWarehouseId()); + } + Map userNames = userIds.isEmpty() ? Map.of() + : userMapper.selectBatchIds(userIds).stream() + .collect(Collectors.toMap(User::getId, User::getName, (a, b) -> a)); + Map agentNames = agentIds.isEmpty() ? Map.of() + : agentMapper.selectBatchIds(agentIds).stream() + .collect(Collectors.toMap(Agent::getId, Agent::getName, (a, b) -> a)); + Map propertyNames = propertyIds.isEmpty() ? Map.of() + : properytMapper.selectBatchIds(propertyIds).stream() + .collect(Collectors.toMap(Properyt::getId, Properyt::getName, (a, b) -> a)); + Map districtNames = districtIds.isEmpty() ? Map.of() + : districtMapper.selectBatchIds(districtIds).stream() + .collect(Collectors.toMap(District::getId, District::getDistrictName, (a, b) -> a)); + Map warehouseNos = warehouseIds.isEmpty() ? Map.of() + : warehouseMapper.selectBatchIds(warehouseIds).stream() + .collect(Collectors.toMap(Warehouse::getId, Warehouse::getWarehouseNo, (a, b) -> a)); + + List events = new ArrayList<>(); + // 未生产(老系统以建档时间呈现生产档案) + Map unproduced = new LinkedHashMap<>(); + unproduced.put("orderNo", sncode.getOrderNo()); + unproduced.put("orderPack", sncode.getOrderPack()); + unproduced.put("materialNo", sncode.getMaterialNo()); + unproduced.put("materielFullName", sncode.getMaterielFullName()); + unproduced.put("nfcBound", sncode.getNfcFlag() != null && sncode.getNfcFlag() != 0); + unproduced.put("sysversion", sncode.getSysversion()); + unproduced.put("hardVersion", sncode.getHardVersion()); + unproduced.put("memo", sncode.getMemo()); + unproduced.put("operator", userNames.get(sncode.getCreateId())); + events.add(new EventItem("unproduced", "未生产", sncode.getCreateTime(), unproduced)); + // 生产中(老系统以解绑时间呈现) + if (sncode.getUnbingTime() != null) { + Map producingFields = new LinkedHashMap<>(); + producingFields.put("operator", userNames.get(sncode.getModifyId())); + events.add(new EventItem("producing", "生产中", sncode.getUnbingTime(), producingFields)); + } + // 生产完成(质检记录;老系统标题"生成完成"为笔误) + if (checkRecord != null) { + Map producedFields = new LinkedHashMap<>(); + producedFields.put("operator", userNames.get(checkRecord.getCreateId())); + events.add(new EventItem("produced", "生产完成", checkRecord.getModifyTime(), producedFields)); + } + // 入库/重工 + for (WarehouseInDetails detail : inDetails) { + boolean rework = REWORK_WAREHOUSE_NO.equals(warehouseNos.get(detail.getWarehouseId())); + Map fields = new LinkedHashMap<>(); + fields.put("inOrderNo", detail.getInOrderNo()); + fields.put("warehouseTypeName", detail.getWarehouseTypeName()); + fields.put("applyUserName", detail.getApplyUserName()); + fields.put("applyTime", format(detail.getCreateTime())); + fields.put("warehouseName", detail.getWarehouseName()); + fields.put("inConfirmUserName", detail.getInConfirmUserName()); + fields.put("inDate", detail.getInDate() == null ? null : detail.getInDate().toString()); + events.add(new EventItem(rework ? "rework" : "inbound", rework ? "重工" : "入库", + detail.getInConfirmTime(), fields)); + } + // 出库/出厂(含发货信息) + for (WarehouseOutDetails detail : outDetails) { + boolean exFactory = EX_FACTORY_WAREHOUSE_NO.equals(warehouseNos.get(detail.getWarehouseId())); + Map fields = new LinkedHashMap<>(); + fields.put("outOrderNo", detail.getOutOrderNo()); + fields.put("warehouseTypeName", detail.getWarehouseTypeName()); + fields.put("applyUserName", detail.getApplyUserName()); + fields.put("applyTime", format(detail.getCreateTime())); + fields.put("warehouseName", detail.getWarehouseName()); + fields.put("useCustomerName", detail.getUseCustomerName()); + fields.put("outConfirmUserName", detail.getOutConfirmUserName()); + fields.put("outDate", detail.getOutDate() == null ? null : detail.getOutDate().toString()); + Map shipping = shipping(detail); + if (shipping != null) { + fields.put("shipping", shipping); + } + events.add(new EventItem(exFactory ? "exFactory" : "outbound", exFactory ? "出厂" : "出库", + detail.getOutConfirmTime(), fields)); + } + // 安装/上线/下线 + for (HardwareInstallLog log : installLogs) { + String[] typeTitle = installTypeTitle(log.getLogType()); + Map fields = new LinkedHashMap<>(); + fields.put("agentName", agentNames.get(log.getAgentId())); + fields.put("propertyName", propertyNames.get(log.getPropertyId())); + fields.put("districtName", districtNames.get(log.getDistrictId())); + fields.put("address", log.getAddress()); + fields.put("operator", userNames.get(log.getCreateId())); + events.add(new EventItem(typeTitle[0], typeTitle[1], log.getOnlineTime(), fields)); + } + // 备用 + for (HardwareLogEsGateway.Record log : backupLogs) { + Map fields = new LinkedHashMap<>(); + fields.put("agentName", agentNames.get(log.getAgentId())); + fields.put("propertyName", propertyNames.get(log.getPropertyId())); + fields.put("districtName", districtNames.get(log.getDistrictId())); + fields.put("event", log.getEvent()); + fields.put("operator", log.getUserName()); + events.add(new EventItem("backup", "备用", null, fields, log.getCreateTime())); + } + + events.sort(Comparator.comparing(EventItem::sortKey, Comparator.nullsLast(Comparator.reverseOrder()))); + + List> eventList = events.stream().map(EventItem::toMap).collect(Collectors.toList()); + output.put("found", true); + output.put("total", eventList.size()); + output.put("events", eventList); + return output; + } + + /** 发货信息:优先 mall_order_no,否则 out_order_no;sendMode 0=快递、1=自行派送,其余不返回。 */ + private Map shipping(WarehouseOutDetails detail) { + String orderNo = StringUtils.hasText(detail.getMallOrderNo()) + ? detail.getMallOrderNo().trim() : detail.getOutOrderNo(); + if (!StringUtils.hasText(orderNo)) { + return null; + } + MallOrderLogistics logistics = mallOrderLogisticsMapper.selectOne( + new LambdaQueryWrapper() + .eq(MallOrderLogistics::getSoftDelete, 0) + .eq(MallOrderLogistics::getOrderNo, orderNo.trim()) + .last("limit 1")); + if (logistics == null || logistics.getSendMode() == null) { + return null; + } + Map shipping = new LinkedHashMap<>(); + if (logistics.getSendMode() == 0) { + shipping.put("mode", "快递"); + // 物流公司名直接用 mall_order_logistics 冗余列,不再 join mall_logistics(刻意简化) + shipping.put("logisticsName", logistics.getLogisticsName()); + shipping.put("logisticsOrderNo", logistics.getLogisticsOrderNo()); + return shipping; + } + if (logistics.getSendMode() == 1) { + shipping.put("mode", "自行派送"); + shipping.put("deliverName", logistics.getDeliverName()); + return shipping; + } + return null; + } + + private static String[] installTypeTitle(Integer logType) { + if (logType != null) { + if (logType == 0) { + return new String[]{"install", "安装"}; + } + if (logType == 1) { + return new String[]{"online", "上线"}; + } + if (logType == 2) { + return new String[]{"offline", "下线"}; + } + } + return new String[]{"unknown", "未知(" + logType + ")"}; + } + + private static void addIfNotNull(Set set, Long... ids) { + for (Long id : ids) { + if (id != null) { + set.add(id); + } + } + } + + private static String enumText(Integer value, String... labels) { + if (value == null) { + return null; + } + return value >= 0 && value < labels.length ? labels[value] : "未知(" + value + ")"; + } + + /** roadState/inventoryState 含 -1=初始化,单独映射。 */ + private static String roadInventoryText(Integer value, String zeroLabel, String oneLabel) { + if (value == null) { + return null; + } + if (value == -1) { + return "初始化"; + } + if (value == 0) { + return zeroLabel; + } + if (value == 1) { + return oneLabel; + } + return "未知(" + value + ")"; + } + + private static String format(Date value) { + return value == null ? null : TIME_FORMATTER.format(value.toInstant()); + } + + /** 聚合中的单条事件;备用机日志时间来自 ES 文本,排序时解析回时间,解析失败兜底沉底。 */ + private static final class EventItem { + private final String type; + private final String title; + private final Date time; + private final String timeText; + private final Map fields; + + EventItem(String type, String title, Date time, Map fields) { + this(type, title, time, fields, null); + } + + EventItem(String type, String title, Date time, Map fields, String timeText) { + this.type = type; + this.title = title; + this.time = time; + this.fields = fields; + this.timeText = timeText; + } + + Date sortKey() { + if (time != null) { + return time; + } + if (timeText != null) { + try { + return Date.from(LocalDateTime.parse(timeText, PARSE_FORMATTER) + .atZone(BUSINESS_ZONE).toInstant()); + } catch (DateTimeParseException ex) { + return null; + } + } + return null; + } + + Map toMap() { + Map map = new LinkedHashMap<>(); + map.put("type", type); + map.put("title", title); + map.put("time", time != null ? format(time) : timeText); + map.put("fields", fields); + return map; + } + } +} diff --git a/xiaoqu-agent-service/src/test/java/me/iiv/agent/es/HardwareLogEsGatewayImplTest.java b/xiaoqu-agent-service/src/test/java/me/iiv/agent/es/HardwareLogEsGatewayImplTest.java new file mode 100644 index 0000000..9278469 --- /dev/null +++ b/xiaoqu-agent-service/src/test/java/me/iiv/agent/es/HardwareLogEsGatewayImplTest.java @@ -0,0 +1,112 @@ +package me.iiv.agent.es; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.util.EntityUtils; +import org.elasticsearch.client.Request; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.RestClient; +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 java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; + +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.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class HardwareLogEsGatewayImplTest { + + @Mock + RestClient cloudRestClient; + + HardwareLogEsGatewayImpl gateway; + + private final ObjectMapper mapper = new ObjectMapper(); + + @BeforeEach + void setUp() { + gateway = new HardwareLogEsGatewayImpl(cloudRestClient); + } + + private static Response esResponse(String jsonBody) throws IOException { + Response response = mock(Response.class); + when(response.getEntity()).thenReturn(new StringEntity(jsonBody, ContentType.APPLICATION_JSON)); + return response; + } + + @Test + void buildsTermQueryOnSnCodeAndBackupLogType() throws Exception { + Response response = esResponse("{\"hits\":{\"hits\":[]}}"); + when(cloudRestClient.performRequest(any(Request.class))).thenReturn(response); + + gateway.findBackupLogs("SN-9", 1000); + + ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + verify(cloudRestClient).performRequest(captor.capture()); + Request captured = captor.getValue(); + assertEquals("POST", captured.getMethod()); + assertEquals("/hardwarelog/_search", captured.getEndpoint()); + JsonNode body = mapper.readTree(EntityUtils.toString(captured.getEntity(), StandardCharsets.UTF_8)); + assertEquals(1000, body.get("size").asInt()); + String filter = body.at("/query/bool/filter").toString(); + assertTrue(filter.contains("\"snCode\":\"SN-9\"")); + assertTrue(filter.contains("\"logType\":\"备用机操作日志\"")); + assertTrue(body.at("/sort").toString().contains("\"id\":{\"order\":\"desc\"}")); + } + + @Test + void mapsHitsAndNormalizesEpochMillisCreateTime() throws Exception { + // 2026-05-01 10:00:00 Asia/Shanghai = 1777168800000L? 用固定值并断言格式即可 + String json = "{\"hits\":{\"hits\":[" + + "{\"_source\":{\"createTime\":1777168800000,\"event\":\"转备用\",\"userName\":\"张三\"," + + "\"agentId\":11,\"propertyId\":\"12\",\"districtId\":13}}," + + "{\"_source\":{\"createTime\":\"2026-05-02 08:30:00\",\"event\":\"解除备用\"," + + "\"userName\":null}}" + + "]}}"; + Response response = esResponse(json); + when(cloudRestClient.performRequest(any(Request.class))).thenReturn(response); + + List records = gateway.findBackupLogs("SN-9", 1000); + + assertEquals(2, records.size()); + HardwareLogEsGateway.Record first = records.get(0); + // epoch 毫秒归一为 yyyy-MM-dd HH:mm:ss 文本 + assertTrue(first.getCreateTime().matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")); + assertEquals("转备用", first.getEvent()); + assertEquals("张三", first.getUserName()); + assertEquals(11L, first.getAgentId()); + // propertyId 文本形态也能解析 + assertEquals(12L, first.getPropertyId()); + assertEquals(13L, first.getDistrictId()); + + HardwareLogEsGateway.Record second = records.get(1); + // 已是文本形态原样返回 + assertEquals("2026-05-02 08:30:00", second.getCreateTime()); + assertNull(second.getUserName()); + assertNull(second.getAgentId()); + } + + @Test + void wrapsEsFailureAsIllegalState() throws Exception { + when(cloudRestClient.performRequest(any(Request.class))).thenThrow(new IOException("boom")); + + IllegalStateException ex = assertThrows(IllegalStateException.class, + () -> gateway.findBackupLogs("SN-9", 1000)); + assertTrue(ex.getMessage().contains("ES 查询备用机操作日志失败")); + } +} diff --git a/xiaoqu-agent-service/src/test/java/me/iiv/agent/mcp/tool/DeviceLifecycleToolsTest.java b/xiaoqu-agent-service/src/test/java/me/iiv/agent/mcp/tool/DeviceLifecycleToolsTest.java new file mode 100644 index 0000000..cdf3cdf --- /dev/null +++ b/xiaoqu-agent-service/src/test/java/me/iiv/agent/mcp/tool/DeviceLifecycleToolsTest.java @@ -0,0 +1,473 @@ +package me.iiv.agent.mcp.tool; + +import com.baomidou.mybatisplus.core.MybatisConfiguration; +import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import me.iiv.agent.entity.m0.Agent; +import me.iiv.agent.entity.m0.DeviceLifeCycle; +import me.iiv.agent.entity.m0.District; +import me.iiv.agent.entity.m0.HardwareCheckRecord; +import me.iiv.agent.entity.m0.HardwareInstallLog; +import me.iiv.agent.entity.m0.HardwareSncode; +import me.iiv.agent.entity.m0.Properyt; +import me.iiv.agent.entity.m0.User; +import me.iiv.agent.entity.m1.MallOrderLogistics; +import me.iiv.agent.entity.m2.Warehouse; +import me.iiv.agent.entity.m2.WarehouseInDetails; +import me.iiv.agent.entity.m2.WarehouseOutDetails; +import me.iiv.agent.es.HardwareLogEsGateway; +import me.iiv.agent.mapper.m0.AgentMapper; +import me.iiv.agent.mapper.m0.DeviceLifeCycleMapper; +import me.iiv.agent.mapper.m0.DistrictMapper; +import me.iiv.agent.mapper.m0.HardwareCheckRecordMapper; +import me.iiv.agent.mapper.m0.HardwareInstallLogMapper; +import me.iiv.agent.mapper.m0.HardwareSncodeMapper; +import me.iiv.agent.mapper.m0.ProperytMapper; +import me.iiv.agent.mapper.m0.UserMapper; +import me.iiv.agent.mapper.m1.MallOrderLogisticsMapper; +import me.iiv.agent.mapper.m2.WarehouseInDetailsMapper; +import me.iiv.agent.mapper.m2.WarehouseMapper; +import me.iiv.agent.mapper.m2.WarehouseOutDetailsMapper; +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.SetOperations; +import org.springframework.data.redis.core.StringRedisTemplate; + +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +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.anyCollection; +import static org.mockito.ArgumentMatchers.eq; +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 DeviceLifecycleToolsTest { + + private static final ZoneId SHANGHAI = ZoneId.of("Asia/Shanghai"); + + @Mock + DeviceLifeCycleMapper deviceLifeCycleMapper; + @Mock + HardwareSncodeMapper hardwareSncodeMapper; + @Mock + HardwareCheckRecordMapper hardwareCheckRecordMapper; + @Mock + HardwareInstallLogMapper hardwareInstallLogMapper; + @Mock + WarehouseInDetailsMapper warehouseInDetailsMapper; + @Mock + WarehouseOutDetailsMapper warehouseOutDetailsMapper; + @Mock + WarehouseMapper warehouseMapper; + @Mock + MallOrderLogisticsMapper mallOrderLogisticsMapper; + @Mock + AgentMapper agentMapper; + @Mock + ProperytMapper properytMapper; + @Mock + DistrictMapper districtMapper; + @Mock + UserMapper userMapper; + @Mock + HardwareLogEsGateway hardwareLogEsGateway; + @Mock + StringRedisTemplate redisTemplate; + @Mock + HashOperations hashOperations; + @Mock + SetOperations setOperations; + + DeviceLifecycleTools tools; + + @BeforeEach + void setUp() { + MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), ""); + TableInfoHelper.initTableInfo(assistant, DeviceLifeCycle.class); + TableInfoHelper.initTableInfo(assistant, HardwareSncode.class); + TableInfoHelper.initTableInfo(assistant, HardwareCheckRecord.class); + TableInfoHelper.initTableInfo(assistant, HardwareInstallLog.class); + TableInfoHelper.initTableInfo(assistant, WarehouseInDetails.class); + TableInfoHelper.initTableInfo(assistant, WarehouseOutDetails.class); + TableInfoHelper.initTableInfo(assistant, MallOrderLogistics.class); + tools = new DeviceLifecycleTools(deviceLifeCycleMapper, hardwareSncodeMapper, + hardwareCheckRecordMapper, hardwareInstallLogMapper, warehouseInDetailsMapper, + warehouseOutDetailsMapper, warehouseMapper, mallOrderLogisticsMapper, + agentMapper, properytMapper, districtMapper, userMapper, + hardwareLogEsGateway, redisTemplate); + } + + // ---------- 工具一:当前状态列表 ---------- + + @Test + void queryRejectsBlankSnCode() { + assertThrows(IllegalArgumentException.class, + () -> tools.hardwareDeviceLifecycleQuery(null, null, null)); + assertThrows(IllegalArgumentException.class, + () -> tools.hardwareDeviceLifecycleQuery(" ", null, null)); + verifyNoInteractions(deviceLifeCycleMapper, redisTemplate); + } + + @Test + void queryTruncatesRowsOverLimitWithNotice() { + Page page = new Page<>(1, 100); + page.setTotal(0); + page.setRecords(List.of()); + when(deviceLifeCycleMapper.selectPage(any(), any())).thenReturn(page); + + Map output = tools.hardwareDeviceLifecycleQuery("SN1", 1, 500); + + assertEquals(100, output.get("rows")); + assertEquals("rows 超过上限 100,已截断为 100", output.get("notice")); + } + + @Test + void queryMapsEnumTextsIncludingUnknownAndInit() { + DeviceLifeCycle cycle = new DeviceLifeCycle(); + cycle.setSnCode("SN-UNKNOWN"); + cycle.setDeviceType(0); + cycle.setExchangeState(3); + cycle.setUpExchangeState(99); + cycle.setRoadState(-1); + cycle.setInventoryState(1); + cycle.setNetworkState(1); + cycle.setAssetState(2); + cycle.setJindieSyncState(0); + Page page = new Page<>(1, 20); + page.setTotal(1); + page.setRecords(List.of(cycle)); + when(deviceLifeCycleMapper.selectPage(any(), any())).thenReturn(page); + + Map output = tools.hardwareDeviceLifecycleQuery("SN-UNKNOWN", null, null); + + @SuppressWarnings("unchecked") + List> records = (List>) output.get("records"); + Map row = records.get(0); + assertEquals("出纸机", row.get("deviceTypeText")); + assertEquals("出厂", row.get("exchangeStateText")); + assertEquals("未知(99)", row.get("upExchangeStateText")); + assertEquals("初始化", row.get("roadStateText")); + assertEquals("在库", row.get("inventoryStateText")); + assertEquals("在线", row.get("networkStateText")); + assertEquals("出租", row.get("assetStateText")); + assertEquals("未同步", row.get("jindieSyncStateText")); + assertNull(row.get("roadDays")); + assertEquals(0, row.get("roadDaysFlag")); + // 非在途:不需要在途阈值,不查 Redis + verifyNoInteractions(redisTemplate); + } + + @Test + void queryComputesRoadDaysAndOverdueFlag() { + DeviceLifeCycle cycle = new DeviceLifeCycle(); + cycle.setSnCode("SN-ROAD"); + cycle.setRoadState(1); + cycle.setRoadDate(Date.from(LocalDate.now(SHANGHAI).minusDays(10) + .atStartOfDay(SHANGHAI).toInstant())); + Page page = new Page<>(1, 20); + page.setTotal(1); + page.setRecords(List.of(cycle)); + when(deviceLifeCycleMapper.selectPage(any(), any())).thenReturn(page); + when(redisTemplate.opsForHash()).thenReturn(hashOperations); + when(hashOperations.get("Dictionary", "MaxRoadDays")).thenReturn("7"); + + Map output = tools.hardwareDeviceLifecycleQuery("SN-ROAD", null, null); + + @SuppressWarnings("unchecked") + List> records = (List>) output.get("records"); + Map row = records.get(0); + assertEquals("在途", row.get("roadStateText")); + assertEquals(10, row.get("roadDays")); + assertEquals(1, row.get("roadDaysFlag")); + } + + @Test + void queryRoadDaysWithinThresholdNotOverdue() { + DeviceLifeCycle cycle = new DeviceLifeCycle(); + cycle.setSnCode("SN-ROAD-OK"); + cycle.setRoadState(1); + cycle.setRoadDate(Date.from(LocalDate.now(SHANGHAI).minusDays(3) + .atStartOfDay(SHANGHAI).toInstant())); + Page page = new Page<>(1, 20); + page.setTotal(1); + page.setRecords(List.of(cycle)); + when(deviceLifeCycleMapper.selectPage(any(), any())).thenReturn(page); + when(redisTemplate.opsForHash()).thenReturn(hashOperations); + when(hashOperations.get("Dictionary", "MaxRoadDays")).thenReturn("7"); + + Map output = tools.hardwareDeviceLifecycleQuery("SN-ROAD-OK", null, null); + + @SuppressWarnings("unchecked") + List> records = (List>) output.get("records"); + assertEquals(3, records.get(0).get("roadDays")); + assertEquals(0, records.get(0).get("roadDaysFlag")); + } + + @Test + void queryFailsFastWhenMaxRoadDaysMissing() { + DeviceLifeCycle cycle = new DeviceLifeCycle(); + cycle.setSnCode("SN-ROAD"); + cycle.setRoadState(1); + cycle.setRoadDate(Date.from(LocalDate.now(SHANGHAI).minusDays(1) + .atStartOfDay(SHANGHAI).toInstant())); + Page page = new Page<>(1, 20); + page.setTotal(1); + page.setRecords(List.of(cycle)); + when(deviceLifeCycleMapper.selectPage(any(), any())).thenReturn(page); + when(redisTemplate.opsForHash()).thenReturn(hashOperations); + when(hashOperations.get("Dictionary", "MaxRoadDays")).thenReturn(null); + + assertThrows(IllegalStateException.class, + () -> tools.hardwareDeviceLifecycleQuery("SN-ROAD", null, null)); + } + + // ---------- 工具二:事件时间线详情 ---------- + + @Test + void detailRejectsBlankSnCode() { + assertThrows(IllegalArgumentException.class, + () -> tools.hardwareDeviceLifecycleDetailQuery(" ")); + verifyNoInteractions(hardwareSncodeMapper, redisTemplate, hardwareLogEsGateway); + } + + @Test + void detailReturnsNotFoundWhenSnMissing() { + when(hardwareSncodeMapper.selectOne(any())).thenReturn(null); + + Map output = tools.hardwareDeviceLifecycleDetailQuery("SN-NONE"); + + assertEquals(false, output.get("found")); + assertEquals(0, output.get("total")); + assertEquals(List.of(), output.get("events")); + assertEquals("hardware_sncode 中不存在该设备编号,未聚合任何事件", output.get("notice")); + verifyNoInteractions(warehouseInDetailsMapper, hardwareLogEsGateway); + } + + @Test + void detailSkipsEsWhenSpecialSncode() { + HardwareSncode sncode = baseSncode(); + when(hardwareSncodeMapper.selectOne(any())).thenReturn(sncode); + when(warehouseInDetailsMapper.selectList(any())).thenReturn(List.of()); + when(warehouseOutDetailsMapper.selectList(any())).thenReturn(List.of()); + when(hardwareCheckRecordMapper.selectOne(any())).thenReturn(null); + when(hardwareInstallLogMapper.selectList(any())).thenReturn(List.of()); + when(redisTemplate.opsForSet()).thenReturn(setOperations); + when(setOperations.isMember("SpecialSncode", "SN-1")).thenReturn(true); + when(userMapper.selectBatchIds(anyCollection())).thenReturn(List.of()); + + Map output = tools.hardwareDeviceLifecycleDetailQuery("SN-1"); + + assertEquals(true, output.get("found")); + verify(hardwareLogEsGateway, never()).findBackupLogs(any(), eq(1000)); + // 只有"未生产"一个事件(无 unbingTime、无质检) + assertEquals(1, output.get("total")); + } + + @Test + void detailAggregatesAllEventSourcesSortedDesc() { + HardwareSncode sncode = baseSncode(); + sncode.setUnbingTime(date("2026-01-02")); + sncode.setModifyId(9L); + + HardwareCheckRecord checkRecord = new HardwareCheckRecord(); + checkRecord.setCreateId(9L); + checkRecord.setModifyTime(date("2026-01-03")); + + WarehouseInDetails inDetail = new WarehouseInDetails(); + inDetail.setWarehouseId(100L); + inDetail.setInOrderNo("IN-1"); + inDetail.setInConfirmTime(date("2026-02-01")); + inDetail.setInDate(LocalDate.of(2026, 2, 1)); + + WarehouseOutDetails outDetail = new WarehouseOutDetails(); + outDetail.setWarehouseId(200L); + outDetail.setOutOrderNo("OUT-1"); + outDetail.setMallOrderNo("MO-1"); + outDetail.setOutConfirmTime(date("2026-03-01")); + outDetail.setOutDate(LocalDate.of(2026, 3, 1)); + + HardwareInstallLog installLog = new HardwareInstallLog(); + installLog.setLogType(0); + installLog.setCreateId(9L); + installLog.setAgentId(11L); + installLog.setPropertyId(12L); + installLog.setDistrictId(13L); + installLog.setOnlineTime(date("2026-04-01")); + + HardwareLogEsGateway.Record backupLog = new HardwareLogEsGateway.Record( + "2026-05-01 10:00:00", "转备用", "张三", 11L, 12L, 13L); + + when(hardwareSncodeMapper.selectOne(any())).thenReturn(sncode); + when(warehouseInDetailsMapper.selectList(any())).thenReturn(List.of(inDetail)); + when(warehouseOutDetailsMapper.selectList(any())).thenReturn(List.of(outDetail)); + when(hardwareCheckRecordMapper.selectOne(any())).thenReturn(checkRecord); + when(hardwareInstallLogMapper.selectList(any())).thenReturn(List.of(installLog)); + when(redisTemplate.opsForSet()).thenReturn(setOperations); + when(setOperations.isMember("SpecialSncode", "SN-1")).thenReturn(false); + when(hardwareLogEsGateway.findBackupLogs("SN-1", 1000)).thenReturn(List.of(backupLog)); + + User user = new User(); + user.setId(9L); + user.setName("操作员甲"); + when(userMapper.selectBatchIds(anyCollection())).thenReturn(List.of(user)); + Agent agent = new Agent(); + agent.setId(11L); + agent.setName("代理商A"); + when(agentMapper.selectBatchIds(anyCollection())).thenReturn(List.of(agent)); + Properyt properyt = new Properyt(); + properyt.setId(12L); + properyt.setName("物业B"); + when(properytMapper.selectBatchIds(anyCollection())).thenReturn(List.of(properyt)); + District district = new District(); + district.setId(13L); + district.setDistrictName("站点C"); + when(districtMapper.selectBatchIds(anyCollection())).thenReturn(List.of(district)); + Warehouse reworkWarehouse = new Warehouse(); + reworkWarehouse.setId(100L); + reworkWarehouse.setWarehouseNo("1000000998"); + Warehouse factoryWarehouse = new Warehouse(); + factoryWarehouse.setId(200L); + factoryWarehouse.setWarehouseNo("BJ001"); + when(warehouseMapper.selectBatchIds(anyCollection())) + .thenReturn(List.of(reworkWarehouse, factoryWarehouse)); + + MallOrderLogistics logistics = new MallOrderLogistics(); + logistics.setSendMode(0); + logistics.setLogisticsName("顺丰"); + logistics.setLogisticsOrderNo("SF123"); + when(mallOrderLogisticsMapper.selectOne(any())).thenReturn(logistics); + + Map output = tools.hardwareDeviceLifecycleDetailQuery("SN-1"); + + assertEquals(true, output.get("found")); + @SuppressWarnings("unchecked") + List> events = (List>) output.get("events"); + // 未生产、生产中、生产完成、重工、出厂、安装、备用 共 7 条,按时间倒序 + assertEquals(7, events.size()); + assertEquals("backup", events.get(0).get("type")); + assertEquals("备用", events.get(0).get("title")); + assertEquals("2026-05-01 10:00:00", events.get(0).get("time")); + assertEquals("install", events.get(1).get("type")); + assertEquals("exFactory", events.get(2).get("type")); + assertEquals("出厂", events.get(2).get("title")); + assertEquals("rework", events.get(3).get("type")); + assertEquals("重工", events.get(3).get("title")); + assertEquals("produced", events.get(4).get("type")); + assertEquals("生产完成", events.get(4).get("title")); + assertEquals("producing", events.get(5).get("type")); + assertEquals("unproduced", events.get(6).get("type")); + + @SuppressWarnings("unchecked") + Map exFactoryFields = (Map) events.get(2).get("fields"); + @SuppressWarnings("unchecked") + Map shipping = (Map) exFactoryFields.get("shipping"); + assertEquals("快递", shipping.get("mode")); + assertEquals("顺丰", shipping.get("logisticsName")); + assertEquals("SF123", shipping.get("logisticsOrderNo")); + + @SuppressWarnings("unchecked") + Map installFields = (Map) events.get(1).get("fields"); + assertEquals("代理商A", installFields.get("agentName")); + assertEquals("物业B", installFields.get("propertyName")); + assertEquals("站点C", installFields.get("districtName")); + assertEquals("操作员甲", installFields.get("operator")); + } + + @Test + void detailShippingSelfDelivered() { + HardwareSncode sncode = baseSncode(); + WarehouseOutDetails outDetail = new WarehouseOutDetails(); + outDetail.setWarehouseId(300L); + outDetail.setOutOrderNo("OUT-2"); + outDetail.setOutConfirmTime(date("2026-03-01")); + + when(hardwareSncodeMapper.selectOne(any())).thenReturn(sncode); + when(warehouseInDetailsMapper.selectList(any())).thenReturn(List.of()); + when(warehouseOutDetailsMapper.selectList(any())).thenReturn(List.of(outDetail)); + when(hardwareCheckRecordMapper.selectOne(any())).thenReturn(null); + when(hardwareInstallLogMapper.selectList(any())).thenReturn(List.of()); + when(redisTemplate.opsForSet()).thenReturn(setOperations); + when(setOperations.isMember("SpecialSncode", "SN-1")).thenReturn(true); + when(userMapper.selectBatchIds(anyCollection())).thenReturn(List.of()); + Warehouse warehouse = new Warehouse(); + warehouse.setId(300L); + warehouse.setWarehouseNo("WH-OTHER"); + when(warehouseMapper.selectBatchIds(anyCollection())).thenReturn(List.of(warehouse)); + MallOrderLogistics logistics = new MallOrderLogistics(); + logistics.setSendMode(1); + logistics.setDeliverName("李四"); + when(mallOrderLogisticsMapper.selectOne(any())).thenReturn(logistics); + + Map output = tools.hardwareDeviceLifecycleDetailQuery("SN-1"); + + @SuppressWarnings("unchecked") + List> events = (List>) output.get("events"); + // 出库(非出厂仓)+ 未生产 + Map outbound = events.stream() + .filter(e -> "outbound".equals(e.get("type"))).findFirst().orElseThrow(); + @SuppressWarnings("unchecked") + Map shipping = (Map) ((Map) outbound.get("fields")) + .get("shipping"); + assertEquals("自行派送", shipping.get("mode")); + assertEquals("李四", shipping.get("deliverName")); + } + + @Test + void detailNullSafeWhenNamesUnresolvable() { + HardwareSncode sncode = baseSncode(); + sncode.setUnbingTime(date("2026-01-02")); + sncode.setModifyId(999L); + + when(hardwareSncodeMapper.selectOne(any())).thenReturn(sncode); + when(warehouseInDetailsMapper.selectList(any())).thenReturn(List.of()); + when(warehouseOutDetailsMapper.selectList(any())).thenReturn(List.of()); + when(hardwareCheckRecordMapper.selectOne(any())).thenReturn(null); + when(hardwareInstallLogMapper.selectList(any())).thenReturn(List.of()); + when(redisTemplate.opsForSet()).thenReturn(setOperations); + when(setOperations.isMember("SpecialSncode", "SN-1")).thenReturn(true); + // 用户表查不到 modifyId=999,operator 必须为 null 而不是抛异常 + when(userMapper.selectBatchIds(anyCollection())).thenReturn(List.of()); + + Map output = tools.hardwareDeviceLifecycleDetailQuery("SN-1"); + + @SuppressWarnings("unchecked") + List> events = (List>) output.get("events"); + Map producing = events.stream() + .filter(e -> "producing".equals(e.get("type"))).findFirst().orElseThrow(); + @SuppressWarnings("unchecked") + Map fields = (Map) producing.get("fields"); + assertTrue(fields.containsKey("operator")); + assertNull(fields.get("operator")); + } + + private HardwareSncode baseSncode() { + HardwareSncode sncode = new HardwareSncode(); + sncode.setSncode("SN-1"); + sncode.setOrderNo("PO-1"); + sncode.setNfcFlag(1); + sncode.setCreateId(9L); + sncode.setCreateTime(date("2026-01-01")); + return sncode; + } + + private static Date date(String day) { + return Date.from(LocalDate.parse(day).atStartOfDay(SHANGHAI).toInstant()); + } +}