feat(mcp): 新增设备生命周期查询工具

- 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
This commit is contained in:
wangheng
2026-09-24 09:40:06 +08:00
parent d95bd4d57c
commit 1f145e0c57
22 changed files with 1843 additions and 0 deletions
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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<Record> 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;
}
}
}
@@ -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<Record> 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<Record> 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;
}
}
}
@@ -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<DeviceLifeCycle> {
}
@@ -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<District> {
}
@@ -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<HardwareCheckRecord> {
}
@@ -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<HardwareInstallLog> {
}
@@ -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<HardwareSncode> {
}
@@ -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<WarehouseInDetails> {
}
@@ -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<Warehouse> {
}
@@ -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<WarehouseOutDetails> {
}
@@ -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<String, Object> 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<DeviceLifeCycle> result = deviceLifeCycleMapper.selectPage(new Page<>(pageNo, pageSize),
new LambdaQueryWrapper<DeviceLifeCycle>()
.eq(DeviceLifeCycle::getSoftDelete, 0)
.like(DeviceLifeCycle::getSnCode, snCode.trim())
.orderByAsc(DeviceLifeCycle::getId));
Integer maxRoadDays = null;
List<Map<String, Object>> 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<String, Object> 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<String, Object> lifecycleRecord(DeviceLifeCycle cycle, Integer maxRoadDays) {
Map<String, Object> 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<String, Object> hardwareDeviceLifecycleDetailQuery(
@ToolParam(description = "设备 SN,必填,非空,精确匹配,自动去空格") String snCode) {
if (!StringUtils.hasText(snCode)) {
throw new IllegalArgumentException("snCode 必填,非空");
}
String sn = snCode.trim();
HardwareSncode sncode = hardwareSncodeMapper.selectOne(new LambdaQueryWrapper<HardwareSncode>()
.eq(HardwareSncode::getSoftDelete, 0)
.eq(HardwareSncode::getSncode, sn)
.last("limit 1"));
Map<String, Object> 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<WarehouseInDetails> inDetails = warehouseInDetailsMapper.selectList(
new LambdaQueryWrapper<WarehouseInDetails>()
.eq(WarehouseInDetails::getSoftDelete, 0)
.eq(WarehouseInDetails::getOrderState, 3)
.eq(WarehouseInDetails::getSnCode, sn));
List<WarehouseOutDetails> outDetails = warehouseOutDetailsMapper.selectList(
new LambdaQueryWrapper<WarehouseOutDetails>()
.eq(WarehouseOutDetails::getSoftDelete, 0)
.eq(WarehouseOutDetails::getOrderState, 3)
.eq(WarehouseOutDetails::getSnCode, sn));
HardwareCheckRecord checkRecord = hardwareCheckRecordMapper.selectOne(
new LambdaQueryWrapper<HardwareCheckRecord>()
.eq(HardwareCheckRecord::getSoftDelete, 0)
.eq(HardwareCheckRecord::getSnCode, sn)
.last("limit 1"));
List<HardwareInstallLog> installLogs = hardwareInstallLogMapper.selectList(
new LambdaQueryWrapper<HardwareInstallLog>()
.eq(HardwareInstallLog::getSoftDelete, 0)
.eq(HardwareInstallLog::getSnCode, sn));
// 备用机日志:SN 在 SpecialSncode 集合中跳过(对齐老系统);ES 异常 fail fast
List<HardwareLogEsGateway.Record> 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<Long> userIds = new HashSet<>();
Set<Long> agentIds = new HashSet<>();
Set<Long> propertyIds = new HashSet<>();
Set<Long> districtIds = new HashSet<>();
Set<Long> 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<Long, String> userNames = userIds.isEmpty() ? Map.of()
: userMapper.selectBatchIds(userIds).stream()
.collect(Collectors.toMap(User::getId, User::getName, (a, b) -> a));
Map<Long, String> agentNames = agentIds.isEmpty() ? Map.of()
: agentMapper.selectBatchIds(agentIds).stream()
.collect(Collectors.toMap(Agent::getId, Agent::getName, (a, b) -> a));
Map<Long, String> propertyNames = propertyIds.isEmpty() ? Map.of()
: properytMapper.selectBatchIds(propertyIds).stream()
.collect(Collectors.toMap(Properyt::getId, Properyt::getName, (a, b) -> a));
Map<Long, String> districtNames = districtIds.isEmpty() ? Map.of()
: districtMapper.selectBatchIds(districtIds).stream()
.collect(Collectors.toMap(District::getId, District::getDistrictName, (a, b) -> a));
Map<Long, String> warehouseNos = warehouseIds.isEmpty() ? Map.of()
: warehouseMapper.selectBatchIds(warehouseIds).stream()
.collect(Collectors.toMap(Warehouse::getId, Warehouse::getWarehouseNo, (a, b) -> a));
List<EventItem> events = new ArrayList<>();
// 未生产(老系统以建档时间呈现生产档案)
Map<String, Object> 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<String, Object> producingFields = new LinkedHashMap<>();
producingFields.put("operator", userNames.get(sncode.getModifyId()));
events.add(new EventItem("producing", "生产中", sncode.getUnbingTime(), producingFields));
}
// 生产完成(质检记录;老系统标题"生成完成"为笔误)
if (checkRecord != null) {
Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<Map<String, Object>> 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<String, Object> 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<MallOrderLogistics>()
.eq(MallOrderLogistics::getSoftDelete, 0)
.eq(MallOrderLogistics::getOrderNo, orderNo.trim())
.last("limit 1"));
if (logistics == null || logistics.getSendMode() == null) {
return null;
}
Map<String, Object> 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<Long> 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<String, Object> fields;
EventItem(String type, String title, Date time, Map<String, Object> fields) {
this(type, title, time, fields, null);
}
EventItem(String type, String title, Date time, Map<String, Object> 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<String, Object> toMap() {
Map<String, Object> 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;
}
}
}