feat(mcp): 新增站点状态修改写工具 district.state.update(REQ-20261117-0008)
This commit is contained in:
@@ -3,7 +3,7 @@
|
||||
## ai-proj 关联信息
|
||||
|
||||
- **ai-proj 项目 ID:224**(项目名 xiaoqu_agent_service)。本仓所有需求/任务创建后应挂到该项目,关联任务前确保任务也在项目 224。
|
||||
- 近期需求示例:REQ-20261117-0003(id 6618,设备转固定资产写工具 device.lifecycle.fixed_asset.update,已上线生产+冒烟通过,prod tool id 74 只绑研发专用 scope 6;拍板:报废(4)与已是固定资产(1)守卫拒绝、null 按库存商品、只写 asset_state/memo/modify_id/modify_time 四列、不联动资产卡片/金蝶;DeviceLifeCycle 实体补 memo 映射)→ 任务 27536;REQ-20261113-0009(id 6550,短信验证码提取 sms.vercode.latest.query,已上线生产+冒烟通过;验证码=登录敏感原语,全平台唯一显式排除业务 scope:prod 只绑研发专用 scope 6(tool id 73)、dev 只绑测试专用 scope)→ 任务 27164;REQ-20261107-0003(id 6443,出库单作废写工具 warehouse.out.void,已上线生产+冒烟通过,只绑研发专用 scope 6)→ 任务 26410;REQ-20261105-0020(id 6390,仓库出入库明细+在库物品 warehouse.out/in.details.list.query、warehouse.hardstock.list.query 3 工具,approved)→ 任务 26101;REQ-20261104-0015(id 6366,清机记录 hardware.cleanlog.list.query,已上线生产+冒烟通过)→ 任务 25998;REQ-20261012-0004(id 5977,空感 toilet.airquality list/detail/metrics/statelog 4 工具,已部署生产+冒烟通过)→ 任务 23488;REQ-20261013-0006(id 5988,代理角色用户查询工具 agent.user.list.query,approved)→ 任务 23566;REQ-20261012-0002(id 5975,客户换纸记录工具 district.paper.trace.list.query,released)→ 任务 23486;REQ-20260924-0009(id 5806,人流量统计工具+统计类限一个月,implementation 完成)→ 任务 22405;REQ-20260924-0003(id 5800,设备生命周期查询工具,implementation 完成)→ 任务 22391;REQ-20260921-0007(id 5778,设备电量消息查询工具,released)→ 任务 22306;REQ-20260919-0003(id 5747,出入库工具复查修复,released)→ 任务 22123。
|
||||
- 近期需求示例:REQ-20261117-0008(id 6623,站点状态修改 district.state.update,已实现并通过 576 个全量测试及 dev 真实「履约→演示→履约」/39 个资产联动恢复,待部署;prod 仅绑 scope 6)→ 任务 27566;REQ-20261117-0003(id 6618,设备转固定资产写工具 device.lifecycle.fixed_asset.update,已上线生产+冒烟通过,prod tool id 74 只绑研发专用 scope 6;拍板:报废(4)与已是固定资产(1)守卫拒绝、null 按库存商品、只写 asset_state/memo/modify_id/modify_time 四列、不联动资产卡片/金蝶;DeviceLifeCycle 实体补 memo 映射)→ 任务 27536;REQ-20261113-0009(id 6550,短信验证码提取 sms.vercode.latest.query,已上线生产+冒烟通过;验证码=登录敏感原语,全平台唯一显式排除业务 scope:prod 只绑研发专用 scope 6(tool id 73)、dev 只绑测试专用 scope)→ 任务 27164;REQ-20261107-0003(id 6443,出库单作废写工具 warehouse.out.void,已上线生产+冒烟通过,只绑研发专用 scope 6)→ 任务 26410;REQ-20261105-0020(id 6390,仓库出入库明细+在库物品 warehouse.out/in.details.list.query、warehouse.hardstock.list.query 3 工具,approved)→ 任务 26101;REQ-20261104-0015(id 6366,清机记录 hardware.cleanlog.list.query,已上线生产+冒烟通过)→ 任务 25998;REQ-20261012-0004(id 5977,空感 toilet.airquality list/detail/metrics/statelog 4 工具,已部署生产+冒烟通过)→ 任务 23488;REQ-20261013-0006(id 5988,代理角色用户查询工具 agent.user.list.query,approved)→ 任务 23566;REQ-20261012-0002(id 5975,客户换纸记录工具 district.paper.trace.list.query,released)→ 任务 23486;REQ-20260924-0009(id 5806,人流量统计工具+统计类限一个月,implementation 完成)→ 任务 22405;REQ-20260924-0003(id 5800,设备生命周期查询工具,implementation 完成)→ 任务 22391;REQ-20260921-0007(id 5778,设备电量消息查询工具,released)→ 任务 22306;REQ-20260919-0003(id 5747,出入库工具复查修复,released)→ 任务 22123。
|
||||
|
||||
## ai-proj MCP 已知限制与真实契约
|
||||
|
||||
|
||||
@@ -107,6 +107,7 @@ xiaoqu-agent-service/
|
||||
| `warehouse.out.void` | admin | write | 出库单作废(研发/运维专用,REQ-20261107-0003,老系统 /myWarehouseOut/remove 的 MCP 化)。入参 outOrderNo/mallOrderNo(至少一个)/memo/confirmMulti;只作废已完成(order_state=3)单,全链路 7 步:主表/明细置作废、库存恢复、商城回滚待出库、SN 硬库存回库+LifeCycle 撤销推送、关联入库单级联作废+扣库存、金蝶作废推送、无安装单时送货工单级联软删;m2 一个事务、m1 提交后执行、Redis 最后且失败不回滚;mallOrderNo 多单需 confirmMulti=true 否则只回候选清单;无行级权限,只绑"研发专用" scope,用户身份 Token 调用。详细设计见 doc/warehouse-out-void-mcp-design.md |
|
||||
| `sms.vercode.latest.query` | admin | read | 短信验证码提取(研发/测试专用,REQ-20261113-0009)。入参 mobile(11 位手机号精确匹配);查 m0 sms_send_record 中 buss_type=验证码+soft_delete=0 的 id DESC 首条,正则 `验证码\s*[=::]\s*(\d{4,8})` 从 sms_content 提取数字码(不命中 vercode=null+原始内容不报错);send_state 不过滤(失败记录也返回并配文案);返回 vercode/sendState/sendStateText/createTime/ageSeconds(供判断 90 秒 redis 有效期);无记录 record=null+notice。验证码=登录敏感原语,零行级权限,全平台唯一显式排除业务 scope 的工具:prod 只绑研发专用 scope 6、dev 只绑测试专用 scope。详细设计见 doc/sms-vercode-latest-mcp-design.md |
|
||||
| `device.lifecycle.fixed_asset.update` | admin | write | 设备转固定资产(研发/运维专用,REQ-20261117-0003)。入参 snCode(精确匹配 sn_code,不模糊);UPDATE m0 device_life_cycle 的 asset_state→1(固定资产),memo 自动写「从<原状态>变成固定资产」,补 modify_id/modify_time;允许来源 0库存/2出租/3售出/5费用化/null,已是固定资产(1)与已报废(4)报错拒绝(目标状态固定 1,固定资产永远不会被改成其他状态);重复 SN 取 id 最早一条;只写 asset_state/memo/modify_id/modify_time 四列,不动 last_op_* 流转字段、不生成资产卡片、不触发金蝶同步;无行级权限,只绑"研发专用" scope,服务身份 Token 拒绝。详细设计见 doc/device-lifecycle-fixed-asset-mcp-design.md |
|
||||
| `district.state.update` | admin | write | 站点状态修改(研发/运维专用,REQ-20261117-0008)。按站点名称/编号精确定位(至少一个,同传须一致,重名报候选);0测试/1履约/3撤机分别强制 testDate/honourDate/weaningDate,2演示禁带日期;同状态拒绝,非目标历史日期保留;m0 事务更新 strategy 与 district 审计字段,m0 提交后联动 m2 测试/履约资产并补审计字段,撤机不动资产;无行级权限,只绑研发专用 scope,服务身份 Token 拒绝。详细设计见 doc/district-state-update-mcp-design.md |
|
||||
|
||||
分页统一规范:page 从 1 开始,rows 默认 20、上限 100,超出截断为 100 并在返回 `notice` 字段提示。
|
||||
|
||||
|
||||
@@ -1312,6 +1312,30 @@
|
||||
|
||||
---
|
||||
|
||||
## 56. district.state.update
|
||||
|
||||
站点状态修改(写操作,REQ-20261117-0008),研发/运维专用。
|
||||
|
||||
- 分类:admin | 类型:写(readOnlyHint=false)
|
||||
- 入参:`districtName`/`districtNumber` 至少一个,分别精确匹配 `district_name`/`district_number`
|
||||
(soft_delete=0);同传必须指向同一站点,名称重名返回候选 `id(编号)`。
|
||||
- 状态与日期:`districtState=0` 测试须传 `testDate`;`1` 履约须传 `honourDate`;
|
||||
`2` 演示禁止携带任何日期;`3` 撤机须传 `weaningDate`。日期使用合法 `yyyy-MM-dd`。
|
||||
- 守卫:同状态重复修改拒绝;`district_strategy` 不存在时报 `DATA_INTEGRITY_ERROR`,不自动创建。
|
||||
- 写入:m0 事务更新 `district_strategy` 的状态、目标日期、modify_id/modify_time,并更新
|
||||
`district` 的 modify_id/modify_time;非目标历史日期列保持原值。
|
||||
- 资产联动:m0 提交后更新 m2 `asset_info` 中该站点 soft_delete=0 且 asset_status∈{1,2} 的资产;
|
||||
测试/演示 → 测试(1),履约 → 履约(2),同时补 modify_id/modify_time;撤机不动资产。
|
||||
跨库不做分布式事务,m2 失败不会回滚已提交的 m0。
|
||||
- 返回:`districtId/districtName/districtNumber/before/after/linkedAssetCount/requestId`,
|
||||
before/after 含状态、状态文案和三个日期。
|
||||
- 权限:零行级权限,prod 只绑研发专用 scope 6(code=code)、dev 只绑测试专用 scope
|
||||
(code=test,seed-dev.sql kind=write 自动段覆盖);必须用户身份 Token,每次调用落 audit_log。
|
||||
|
||||
详细设计见 [district-state-update-mcp-design](district-state-update-mcp-design.md)。
|
||||
|
||||
---
|
||||
|
||||
## 附录:在线查看工具清单
|
||||
|
||||
```bash
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
# 站点状态修改工具 district.state.update — MCP 设计文档
|
||||
|
||||
- 需求:REQ-20261117-0008
|
||||
- 工具:`district.state.update`(kind=write,category=admin)
|
||||
- 数据源:m0 `district`(站点主表)+ m0 `district_strategy`(站点策略表)+ m2 `asset_info`(资产联动)
|
||||
- 对标老接口:`POST /district/setDistrictAttribute`(`DistrictController.java:780-892`,xiaoqu-franchisee)
|
||||
|
||||
## 1. 背景
|
||||
|
||||
运营需要修改站点状态(测试/履约/演示/撤机)。老系统通过「设置站点属性」页面走
|
||||
`setDistrictAttribute` 完成,该接口同时承担销售类型、耗材价格、账期、SKU 等多个字段的更新,
|
||||
是一个多字段共用的写接口。本工具只抽取其中**站点状态 + 三个日期**这一个语义,做成单职责的
|
||||
研发/运营写工具:零行级权限,只绑研发专用 scope 6。
|
||||
|
||||
## 2. 表结构与老接口行为
|
||||
|
||||
### 2.1 district(m0)
|
||||
|
||||
| 列 | 说明 |
|
||||
|---|---|
|
||||
| id | 站点 id |
|
||||
| district_name | 站点名称(可重名) |
|
||||
| district_number | 站点编号 |
|
||||
| modify_id / modify_time | 最后修改人 / 修改时间 |
|
||||
| soft_delete | 0 正常 |
|
||||
|
||||
### 2.2 district_strategy(m0,一个站点一条策略,老代码 `district_id + soft_delete=0 limit 1`)
|
||||
|
||||
| 列 | 说明 |
|
||||
|---|---|
|
||||
| district_state | 站点状态:0测试 / 1履约 / 2演示 / 3撤机 |
|
||||
| test_date | 测试日期(LocalDate) |
|
||||
| honour_date | 履约日期(LocalDate) |
|
||||
| weaning_date | 撤机日期(LocalDate) |
|
||||
| modify_id / modify_time | 最后修改人 / 修改时间 |
|
||||
|
||||
### 2.3 老接口 setDistrictAttribute 的状态相关逻辑(DistrictController.java:819-856)
|
||||
|
||||
1. `BeanUtils.copyProperties(input, districtStrategy)`:input 的同名字段(含 null)覆盖到 strategy,
|
||||
只 set modify_time(**漏写 modify_id**)。因此未传的非目标日期列可能被清空。
|
||||
2. **资产联动**(:828-853):仅当旧 state 非 null 且与新 state 不等、且新 state < 3(非撤机)时:
|
||||
- 查 m2 `asset_info`(district_id,soft_delete=0);
|
||||
- 只处理 `asset_status ∈ {1测试, 2履约}` 的资产;
|
||||
- 新 state 为 0(测试)或 2(演示)→ `asset_status = 1(测试)`;
|
||||
- 新 state 为 1(履约)→ `asset_status = 2(履约)`;
|
||||
- 撤机(3)不动资产;
|
||||
- 资产只 set assetStatus,**不写 modify_id/modify_time**。
|
||||
3. 同接口还更新 district 主表 modify_id/modify_time(:800-802)。
|
||||
4. 状态与日期**没有强制对应校验**:老接口允许只改日期不改状态、改状态不带日期。
|
||||
5. strategy 不存在时,老接口在 :828 直接触发 NPE;本工具改为明确报错,不自动创建。
|
||||
|
||||
### 2.4 调研结论
|
||||
|
||||
- 老接口是多字段共用,没有独立的"只改状态"入口;本工具收窄语义并补齐校验。
|
||||
- 资产联动是老系统的既有业务规则(演示/测试站点的固定资产视为测试资产,履约站点视为履约资产),
|
||||
不做联动会造成站点状态与资产状态不一致。
|
||||
- 本地实体变更(遵循"实体拷贝到本地包"约定):
|
||||
- `me.iiv.agent.entity.m0.District` 补 `district_number`、`modify_id`、`modify_time`;
|
||||
- 已有 `me.iiv.agent.entity.m0.DistrictStrategy` 物理表实体补状态、日期和修改字段;
|
||||
`DistrictDistrictStrategy` 是 `district_district_strategy` **视图**实体,不能写;
|
||||
- 新增 `me.iiv.agent.entity.m2.AssetInfo`(仅本工具所需列)。
|
||||
|
||||
## 3. 工具契约
|
||||
|
||||
### 3.1 入参
|
||||
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| districtName | string | 条件必填 | 站点名称,**精确匹配** `district_name`(soft_delete=0)。与 districtNumber 至少传一个 |
|
||||
| districtNumber | string | 条件必填 | 站点编号,**精确匹配** `district_number`(soft_delete=0)。与 districtName 至少传一个 |
|
||||
| districtState | int | 是 | 目标状态:0测试 / 1履约 / 2演示 / 3撤机 |
|
||||
| testDate | string(yyyy-MM-dd) | state=0 必填 | 测试日期 |
|
||||
| honourDate | string(yyyy-MM-dd) | state=1 必填 | 履约日期 |
|
||||
| weaningDate | string(yyyy-MM-dd) | state=3 必填 | 撤机日期 |
|
||||
|
||||
校验规则:
|
||||
|
||||
1. `districtName` / `districtNumber` 都未传 → `INVALID_ARGUMENT`「站点名称与站点编号至少传一个」。
|
||||
2. 两个都传:分别解析,必须指向**同一个** district.id,否则 `INVALID_ARGUMENT` 报两边各自命中。
|
||||
3. 名称匹配多条(重名站点)→ `INVALID_ARGUMENT`,报错附候选 `id(编号)` 列表,引导改用编号。
|
||||
4. 名称/编号无匹配 → `NOT_FOUND_OR_FORBIDDEN`「站点不存在」。
|
||||
5. 编号匹配多条 → `DATA_INTEGRITY_ERROR`,不静默选一条。
|
||||
6. `districtState` 非法值 → `INVALID_ARGUMENT`。
|
||||
7. 目标状态所需日期缺失、不是 `yyyy-MM-dd` 或不是合法日历日期 → `INVALID_ARGUMENT`。
|
||||
8. state=2(演示)携带任何日期参数 → `INVALID_ARGUMENT`「修改为演示状态不需要携带日期」。
|
||||
9. 目标状态与当前状态相同 → `INVALID_ARGUMENT`「站点当前已是 xx 状态」,防止无意义覆盖日期。
|
||||
10. `district_strategy` 不存在(district_id + soft_delete=0 查不到)→ `DATA_INTEGRITY_ERROR`
|
||||
「站点策略记录不存在」,不自动创建。
|
||||
11. state=0/1/3 时,非目标日期入参不写入;只更新目标状态对应的日期列。
|
||||
|
||||
### 3.2 行为
|
||||
|
||||
1. 解析站点 → 查 strategy → 校验(上述规则)。
|
||||
2. 在 m0 事务中先更新 `district_strategy`:`district_state` + 目标状态对应的那一个日期列 +
|
||||
`modify_id`(token 用户 id)+ `modify_time`;其余两个日期列保持原值不动。
|
||||
3. 在同一 m0 事务中更新 `district` 主表 `modify_id`/`modify_time`;任一影响行数不是 1 即回滚 m0。
|
||||
4. m0 提交后执行 m2 **资产联动**:
|
||||
- 触发条件:新旧 state 不等且新 state < 3(同状态已在前置校验拒绝);
|
||||
- 范围:该站点 `asset_info`(soft_delete=0)中 `asset_status ∈ {1, 2}` 的资产;
|
||||
- 映射:新 state 0/2 → asset_status=1;新 state 1 → asset_status=2;
|
||||
- 联动资产补写 modify_id/modify_time;
|
||||
- m0/m2 跨库不做分布式事务;m2 失败时报错并落审计,已提交的 m0 不回滚。
|
||||
5. `GuardedToolCallback` 自动向 svc `audit_log` 落调用审计(用户、token、工具、入参摘要、结果、耗时);
|
||||
业务日志记录站点、新旧状态、联动资产数和 request_id。
|
||||
|
||||
### 3.3 返回
|
||||
|
||||
```json
|
||||
{
|
||||
"districtId": 2803,
|
||||
"districtName": "测试望京SOHO",
|
||||
"districtNumber": "xxx",
|
||||
"before": { "districtState": 0, "districtStateText": "测试", "testDate": "2026-01-01", "honourDate": null, "weaningDate": null },
|
||||
"after": { "districtState": 1, "districtStateText": "履约", "testDate": "2026-01-01", "honourDate": "2026-11-17", "weaningDate": null },
|
||||
"linkedAssetCount": 12,
|
||||
"requestId": "uuid"
|
||||
}
|
||||
```
|
||||
|
||||
## 4. 权限与 scope
|
||||
|
||||
- 零行级权限,门禁完全靠 scope。
|
||||
- **prod 只绑研发专用 scope 6(code=code)**;dev 绑测试专用 scope(seed-dev.sql 的
|
||||
kind=write 自动绑定段已覆盖)。不绑任何业务 scope(1/2/3/5)。
|
||||
- 仅用户委托 Token;服务身份 Token 在工具内再次拒绝,确保 modify_id 可追溯。
|
||||
|
||||
## 5. 决策与实施结论
|
||||
|
||||
2026-11-18 按用户「继续开发」指示,采用原设计建议值实施。
|
||||
|
||||
| # | 决策点 | 结论 |
|
||||
|---|---|---|
|
||||
| 1 | 资产联动是否复刻 | **复刻**;联动资产补写 modify 列 |
|
||||
| 2 | 同名站点 | **报错附候选 `id(编号)` 列表**,引导用编号 |
|
||||
| 3 | 同状态重复修改 | **报错拒绝**,防止误覆盖日期 |
|
||||
| 4 | state=2 携带日期 | **报错拒绝** |
|
||||
| 5 | 非目标状态的历史日期列 | **保留原值不动**,修复老接口 copyProperties 可能清空日期的问题 |
|
||||
| 6 | strategy 不存在 | **报错**,不自动创建 |
|
||||
|
||||
## 6. 与老系统差异汇总
|
||||
|
||||
| 差异 | 说明 |
|
||||
|---|---|
|
||||
| 语义收窄 | 只改状态+日期,不碰老接口的销售类型/耗材/账期/SKU |
|
||||
| 状态-日期强校验 | 老接口不校验;本工具按目标状态强制必填对应日期、演示拒收日期 |
|
||||
| 同状态拒绝 | 老接口允许重复写;本工具拒绝 |
|
||||
| 历史日期保留 | 老接口 copyProperties 会用 null 覆盖;本工具只写目标日期列 |
|
||||
| strategy 补写 modify_id | 老接口只写 modify_time |
|
||||
| 联动资产补写 modify_id/modify_time | 老接口不写 |
|
||||
| m0 写入事务 | strategy 与 district 审计字段在同一 m0 事务中更新 |
|
||||
| 名称/编号双路径解析+重名拒绝 | 老接口只按 id 入参 |
|
||||
|
||||
## 7. 测试要点
|
||||
|
||||
1. 参数校验:两定位参数全空 / state 非法 / 缺对应日期 / 演示带日期 / 日期格式非法。
|
||||
2. 解析:名称唯一命中 / 名称重名报候选 / 编号命中 / 两参一致与不一致 / 不存在。
|
||||
3. 守卫:服务 Token 拒绝;同状态拒绝;strategy 不存在。
|
||||
4. 写路径:各状态迁移的日期列写入正确、其余日期列不动、modify_id/modify_time 写入。
|
||||
5. 资产联动:state<3 时 asset_status∈{1,2} 的资产被正确映射(0/2→1、1→2),
|
||||
asset_status∈{0,3} 的不动;state=3 完全不动资产;联动资产 modify 列写入。
|
||||
6. district 主表 modify 列更新;m0 第二步失败时回滚且不联动资产。
|
||||
7. 工具注册元数据与真实 MCP 调用的 scope、audit_log 审计。
|
||||
|
||||
## 8. 上线步骤(按 AGENTS.md 标准流程)
|
||||
|
||||
实现 → 单测 → `./mvnw clean package` 全绿 → 测试环境(test-up.sh + scopeCode=test)写冒烟
|
||||
(真实站点改状态+改回、DB 复核恢复)→ push main → remote-deploy → 确认 ToolSyncService 新增
|
||||
→ prod 绑 scope_tool(6, tool_id)(INSERT IGNORE)→ 生产只读核验(tools/list 可见、错误路径用例)
|
||||
→ ai-proj 收尾(released + 实施记录)。
|
||||
@@ -11,6 +11,8 @@ import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
@@ -42,4 +44,9 @@ public class M0DataSourceConfig {
|
||||
bean.setPlugins(syncQueryTimeoutInterceptor);
|
||||
return bean.getObject();
|
||||
}
|
||||
|
||||
@Bean(name = "m0TransactionManager")
|
||||
public PlatformTransactionManager m0TransactionManager(@Qualifier("m0DataSource") DataSource dataSource) {
|
||||
return new DataSourceTransactionManager(dataSource);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,9 @@ import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/** 站点(m0.district),生命周期详情只取名称。 */
|
||||
/** 站点(m0.district)。 */
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@@ -20,6 +21,9 @@ public class District implements Serializable {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
private Long modifyId;
|
||||
private Date modifyTime;
|
||||
private Integer softDelete;
|
||||
private String districtName;
|
||||
private String districtNumber;
|
||||
}
|
||||
|
||||
@@ -8,12 +8,10 @@ import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* district_strategy 站点策略(m0 库 xiaoqu_comples_d;老系统 beans/b0 走 dataSource0,
|
||||
* 行 id=站点 id,与 district_district_strategy 一一对应)。
|
||||
* 本服务只取 rfid_use_flag 判断换纸卷数口径。
|
||||
*/
|
||||
/** district_strategy 站点策略(m0 物理表)。 */
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@@ -31,6 +29,14 @@ public class DistrictStrategy implements Serializable {
|
||||
/** rfid使用标记(0:未使用;1:使用) */
|
||||
private Integer rfidUseFlag;
|
||||
|
||||
private LocalDate testDate;
|
||||
private LocalDate honourDate;
|
||||
private LocalDate weaningDate;
|
||||
/** 站点状态(0:测试;1:履约;2:演示;3:撤机) */
|
||||
private Integer districtState;
|
||||
private Long modifyId;
|
||||
private Date modifyTime;
|
||||
|
||||
/** 数据状态 */
|
||||
private Integer softDelete;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
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.util.Date;
|
||||
|
||||
/** 固定资产(m2.asset_info)。 */
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@TableName("asset_info")
|
||||
public class AssetInfo implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
private Long modifyId;
|
||||
private Date modifyTime;
|
||||
private Integer softDelete;
|
||||
/** 资产状态(0:在库;1:测试;2:履约;3:领用) */
|
||||
private Integer assetStatus;
|
||||
private Long districtId;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package me.iiv.agent.mapper.m2;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import me.iiv.agent.entity.m2.AssetInfo;
|
||||
|
||||
public interface AssetInfoMapper extends BaseMapper<AssetInfo> {
|
||||
}
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
package me.iiv.agent.mcp.tool;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import me.iiv.agent.entity.m0.District;
|
||||
import me.iiv.agent.entity.m0.DistrictStrategy;
|
||||
import me.iiv.agent.entity.m0.User;
|
||||
import me.iiv.agent.entity.m2.AssetInfo;
|
||||
import me.iiv.agent.mapper.m0.DistrictMapper;
|
||||
import me.iiv.agent.mapper.m0.DistrictStrategyMapper;
|
||||
import me.iiv.agent.mapper.m2.AssetInfoMapper;
|
||||
import me.iiv.agent.mcp.McpCallContextHolder;
|
||||
import me.iiv.agent.mcp.McpErrorCode;
|
||||
import me.iiv.agent.mcp.ToolCallException;
|
||||
import me.iiv.agent.mcp.ToolObject;
|
||||
import me.iiv.agent.mcp.XqTool;
|
||||
import me.iiv.agent.security.AuthContextHolder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.ai.tool.annotation.Tool;
|
||||
import org.springframework.ai.tool.annotation.ToolParam;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 站点状态修改工具(REQ-20261117-0008)。
|
||||
* m0 的 strategy/district 写入使用同一事务;m2 资产联动在 m0 提交后执行,跨库不做分布式事务。
|
||||
*/
|
||||
@Component
|
||||
public class DistrictStateAdminTools implements ToolObject {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DistrictStateAdminTools.class);
|
||||
|
||||
private static final Map<Integer, String> STATE_TEXT = Map.of(
|
||||
0, "测试", 1, "履约", 2, "演示", 3, "撤机");
|
||||
|
||||
final DistrictMapper districtMapper;
|
||||
final DistrictStrategyMapper districtStrategyMapper;
|
||||
final AssetInfoMapper assetInfoMapper;
|
||||
final TransactionTemplate m0Tx;
|
||||
|
||||
public DistrictStateAdminTools(DistrictMapper districtMapper,
|
||||
DistrictStrategyMapper districtStrategyMapper,
|
||||
AssetInfoMapper assetInfoMapper,
|
||||
@Qualifier("m0TransactionManager") PlatformTransactionManager m0TransactionManager) {
|
||||
this.districtMapper = districtMapper;
|
||||
this.districtStrategyMapper = districtStrategyMapper;
|
||||
this.assetInfoMapper = assetInfoMapper;
|
||||
this.m0Tx = new TransactionTemplate(m0TransactionManager);
|
||||
}
|
||||
|
||||
@XqTool(category = "admin", kind = "write")
|
||||
@Tool(name = "district.state.update", description = "【写操作·研发/运维专用】修改站点状态及对应日期。"
|
||||
+ "按 districtName(站点名称)或 districtNumber(站点编号)精确匹配,至少传一个;"
|
||||
+ "名称重名会返回候选 id(编号),两个定位参数都传时必须指向同一站点。"
|
||||
+ "状态:0测试(testDate 必填)/1履约(honourDate 必填)/2演示(禁止携带日期)/3撤机(weaningDate 必填);"
|
||||
+ "日期格式 yyyy-MM-dd。同状态重复修改拒绝,非目标历史日期列保持原值,策略不存在时报错且不自动创建。"
|
||||
+ "新状态为测试/演示时联动测试、履约资产为测试;履约时联动为履约;撤机不动资产。"
|
||||
+ "无行级权限校验,访问控制靠 scope 绑定;必须用户身份 Token,每次调用写审计日志。")
|
||||
public Map<String, Object> stateUpdate(
|
||||
@ToolParam(required = false, description = "站点名称,精确匹配;与 districtNumber 至少传一个") String districtName,
|
||||
@ToolParam(required = false, description = "站点编号,精确匹配;与 districtName 至少传一个") String districtNumber,
|
||||
@ToolParam(description = "目标状态:0测试 1履约 2演示 3撤机") Integer districtState,
|
||||
@ToolParam(required = false, description = "测试日期 yyyy-MM-dd;districtState=0 时必填") String testDate,
|
||||
@ToolParam(required = false, description = "履约日期 yyyy-MM-dd;districtState=1 时必填") String honourDate,
|
||||
@ToolParam(required = false, description = "撤机日期 yyyy-MM-dd;districtState=3 时必填") String weaningDate) {
|
||||
String name = trimToNull(districtName);
|
||||
String number = trimToNull(districtNumber);
|
||||
if (name == null && number == null) {
|
||||
throw new ToolCallException(McpErrorCode.INVALID_ARGUMENT, "站点名称与站点编号至少传一个");
|
||||
}
|
||||
if (districtState == null || !STATE_TEXT.containsKey(districtState)) {
|
||||
throw new ToolCallException(McpErrorCode.INVALID_ARGUMENT, "districtState 必须是 0/1/2/3");
|
||||
}
|
||||
if (districtState == 2 && (testDate != null || honourDate != null || weaningDate != null)) {
|
||||
throw new ToolCallException(McpErrorCode.INVALID_ARGUMENT, "修改为演示状态不需要携带日期");
|
||||
}
|
||||
LocalDate targetDate = switch (districtState) {
|
||||
case 0 -> parseDate(testDate, "testDate");
|
||||
case 1 -> parseDate(honourDate, "honourDate");
|
||||
case 3 -> parseDate(weaningDate, "weaningDate");
|
||||
default -> null;
|
||||
};
|
||||
|
||||
User caller = AuthContextHolder.get().getUser();
|
||||
if (caller == null) {
|
||||
throw new ToolCallException(McpErrorCode.PERMISSION_DENIED,
|
||||
"该工具要求用户身份 Token 调用(操作人需可追溯),服务身份 Token 不可用");
|
||||
}
|
||||
|
||||
District district = locateDistrict(name, number);
|
||||
DistrictStrategy strategy = districtStrategyMapper.selectOne(new LambdaQueryWrapper<DistrictStrategy>()
|
||||
.eq(DistrictStrategy::getSoftDelete, 0)
|
||||
.eq(DistrictStrategy::getDistrictId, district.getId())
|
||||
.last("LIMIT 1"));
|
||||
if (strategy == null) {
|
||||
throw new ToolCallException(McpErrorCode.DATA_INTEGRITY_ERROR, "站点策略记录不存在");
|
||||
}
|
||||
if (Integer.valueOf(districtState).equals(strategy.getDistrictState())) {
|
||||
throw new ToolCallException(McpErrorCode.INVALID_ARGUMENT,
|
||||
"站点当前已是 " + STATE_TEXT.get(districtState) + " 状态");
|
||||
}
|
||||
|
||||
Map<String, Object> before = stateSnapshot(strategy.getDistrictState(), strategy.getTestDate(),
|
||||
strategy.getHonourDate(), strategy.getWeaningDate());
|
||||
Date now = new Date();
|
||||
m0Tx.executeWithoutResult(status -> {
|
||||
updateStrategy(strategy.getId(), districtState, targetDate, caller.getId(), now);
|
||||
updateDistrictAudit(district.getId(), caller.getId(), now);
|
||||
});
|
||||
int linkedAssetCount = linkAssets(district.getId(), districtState, caller.getId(), now);
|
||||
|
||||
Map<String, Object> after = stateSnapshot(districtState,
|
||||
districtState == 0 ? targetDate : strategy.getTestDate(),
|
||||
districtState == 1 ? targetDate : strategy.getHonourDate(),
|
||||
districtState == 3 ? targetDate : strategy.getWeaningDate());
|
||||
String requestId = McpCallContextHolder.currentOrCreateRequestId();
|
||||
log.info("district.state.update 完成 requestId={} districtId={} state={}→{} linkedAssetCount={} caller={}",
|
||||
requestId, district.getId(), strategy.getDistrictState(), districtState, linkedAssetCount, caller.getId());
|
||||
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("districtId", district.getId());
|
||||
result.put("districtName", district.getDistrictName());
|
||||
result.put("districtNumber", district.getDistrictNumber());
|
||||
result.put("before", before);
|
||||
result.put("after", after);
|
||||
result.put("linkedAssetCount", linkedAssetCount);
|
||||
result.put("requestId", requestId);
|
||||
return result;
|
||||
}
|
||||
|
||||
private District locateDistrict(String name, String number) {
|
||||
District byName = name == null ? null : locateByName(name);
|
||||
District byNumber = number == null ? null : locateByNumber(number);
|
||||
if (byName != null && byNumber != null && !byName.getId().equals(byNumber.getId())) {
|
||||
throw new ToolCallException(McpErrorCode.INVALID_ARGUMENT,
|
||||
"站点名称与站点编号指向不同站点:名称=" + candidate(byName) + ",编号=" + candidate(byNumber));
|
||||
}
|
||||
return byNumber != null ? byNumber : byName;
|
||||
}
|
||||
|
||||
private District locateByName(String name) {
|
||||
List<District> rows = districtMapper.selectList(new LambdaQueryWrapper<District>()
|
||||
.eq(District::getSoftDelete, 0)
|
||||
.eq(District::getDistrictName, name)
|
||||
.orderByAsc(District::getId));
|
||||
if (rows.isEmpty()) {
|
||||
throw new ToolCallException(McpErrorCode.NOT_FOUND_OR_FORBIDDEN, "站点不存在");
|
||||
}
|
||||
if (rows.size() > 1) {
|
||||
String candidates = rows.stream().map(DistrictStateAdminTools::candidate)
|
||||
.collect(Collectors.joining(", "));
|
||||
throw new ToolCallException(McpErrorCode.INVALID_ARGUMENT,
|
||||
"站点名称命中多条记录,请改用 districtNumber;候选:" + candidates);
|
||||
}
|
||||
return rows.get(0);
|
||||
}
|
||||
|
||||
private District locateByNumber(String number) {
|
||||
List<District> rows = districtMapper.selectList(new LambdaQueryWrapper<District>()
|
||||
.eq(District::getSoftDelete, 0)
|
||||
.eq(District::getDistrictNumber, number)
|
||||
.orderByAsc(District::getId));
|
||||
if (rows.isEmpty()) {
|
||||
throw new ToolCallException(McpErrorCode.NOT_FOUND_OR_FORBIDDEN, "站点不存在");
|
||||
}
|
||||
if (rows.size() > 1) {
|
||||
throw new ToolCallException(McpErrorCode.DATA_INTEGRITY_ERROR,
|
||||
"站点编号命中多条记录,请携带 request_id 联系运维排查");
|
||||
}
|
||||
return rows.get(0);
|
||||
}
|
||||
|
||||
private void updateStrategy(Long id, int state, LocalDate targetDate, Long callerId, Date now) {
|
||||
LambdaUpdateWrapper<DistrictStrategy> update = new LambdaUpdateWrapper<DistrictStrategy>()
|
||||
.eq(DistrictStrategy::getId, id)
|
||||
.eq(DistrictStrategy::getSoftDelete, 0)
|
||||
.set(DistrictStrategy::getDistrictState, state)
|
||||
.set(DistrictStrategy::getModifyId, callerId)
|
||||
.set(DistrictStrategy::getModifyTime, now);
|
||||
switch (state) {
|
||||
case 0 -> update.set(DistrictStrategy::getTestDate, targetDate);
|
||||
case 1 -> update.set(DistrictStrategy::getHonourDate, targetDate);
|
||||
case 3 -> update.set(DistrictStrategy::getWeaningDate, targetDate);
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
int updated = districtStrategyMapper.update(null, update);
|
||||
if (updated != 1) {
|
||||
throw new ToolCallException(McpErrorCode.DATA_INTEGRITY_ERROR,
|
||||
"站点策略更新影响行数=" + updated + ",预期 1");
|
||||
}
|
||||
}
|
||||
|
||||
private void updateDistrictAudit(Long id, Long callerId, Date now) {
|
||||
int updated = districtMapper.update(null, new LambdaUpdateWrapper<District>()
|
||||
.eq(District::getId, id)
|
||||
.eq(District::getSoftDelete, 0)
|
||||
.set(District::getModifyId, callerId)
|
||||
.set(District::getModifyTime, now));
|
||||
if (updated != 1) {
|
||||
throw new ToolCallException(McpErrorCode.DATA_INTEGRITY_ERROR,
|
||||
"站点主表更新影响行数=" + updated + ",预期 1");
|
||||
}
|
||||
}
|
||||
|
||||
private int linkAssets(Long districtId, int state, Long callerId, Date now) {
|
||||
if (state == 3) {
|
||||
return 0;
|
||||
}
|
||||
int assetStatus = state == 1 ? 2 : 1;
|
||||
return assetInfoMapper.update(null, new LambdaUpdateWrapper<AssetInfo>()
|
||||
.eq(AssetInfo::getDistrictId, districtId)
|
||||
.eq(AssetInfo::getSoftDelete, 0)
|
||||
.in(AssetInfo::getAssetStatus, 1, 2)
|
||||
.set(AssetInfo::getAssetStatus, assetStatus)
|
||||
.set(AssetInfo::getModifyId, callerId)
|
||||
.set(AssetInfo::getModifyTime, now));
|
||||
}
|
||||
|
||||
private static LocalDate parseDate(String value, String param) {
|
||||
String text = trimToNull(value);
|
||||
if (text == null) {
|
||||
throw new ToolCallException(McpErrorCode.INVALID_ARGUMENT, param + " 必填,格式 yyyy-MM-dd");
|
||||
}
|
||||
if (!text.matches("\\d{4}-\\d{2}-\\d{2}")) {
|
||||
throw new ToolCallException(McpErrorCode.INVALID_ARGUMENT, param + " 格式必须是 yyyy-MM-dd");
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(text, DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new ToolCallException(McpErrorCode.INVALID_ARGUMENT, param + " 不是合法日期");
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, Object> stateSnapshot(Integer state, LocalDate testDate,
|
||||
LocalDate honourDate, LocalDate weaningDate) {
|
||||
Map<String, Object> snapshot = new LinkedHashMap<>();
|
||||
snapshot.put("districtState", state);
|
||||
snapshot.put("districtStateText", stateText(state));
|
||||
snapshot.put("testDate", formatDate(testDate));
|
||||
snapshot.put("honourDate", formatDate(honourDate));
|
||||
snapshot.put("weaningDate", formatDate(weaningDate));
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private static String formatDate(LocalDate date) {
|
||||
return date == null ? null : date.format(DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
}
|
||||
|
||||
private static String stateText(Integer state) {
|
||||
return state == null ? null : STATE_TEXT.getOrDefault(state, "未知");
|
||||
}
|
||||
|
||||
private static String candidate(District district) {
|
||||
return district.getId() + "(" + district.getDistrictNumber() + ")";
|
||||
}
|
||||
|
||||
private static String trimToNull(String value) {
|
||||
return StringUtils.hasText(value) ? value.trim() : null;
|
||||
}
|
||||
}
|
||||
+347
@@ -0,0 +1,347 @@
|
||||
package me.iiv.agent.mcp.tool;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import me.iiv.agent.entity.m0.District;
|
||||
import me.iiv.agent.entity.m0.DistrictStrategy;
|
||||
import me.iiv.agent.entity.m0.User;
|
||||
import me.iiv.agent.entity.m2.AssetInfo;
|
||||
import me.iiv.agent.mapper.m0.DistrictMapper;
|
||||
import me.iiv.agent.mapper.m0.DistrictStrategyMapper;
|
||||
import me.iiv.agent.mapper.m2.AssetInfoMapper;
|
||||
import me.iiv.agent.mcp.McpErrorCode;
|
||||
import me.iiv.agent.mcp.ToolCallException;
|
||||
import me.iiv.agent.mcp.XqTool;
|
||||
import me.iiv.agent.security.AuthContext;
|
||||
import me.iiv.agent.security.AuthContextHolder;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
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 org.springframework.ai.tool.annotation.Tool;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionStatus;
|
||||
|
||||
import java.time.LocalDate;
|
||||
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.assertNotNull;
|
||||
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.isNull;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class DistrictStateAdminToolsTest {
|
||||
|
||||
@Mock DistrictMapper districtMapper;
|
||||
@Mock DistrictStrategyMapper districtStrategyMapper;
|
||||
@Mock AssetInfoMapper assetInfoMapper;
|
||||
@Mock PlatformTransactionManager m0TransactionManager;
|
||||
@Mock TransactionStatus transactionStatus;
|
||||
|
||||
DistrictStateAdminTools tools;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
|
||||
TableInfoHelper.initTableInfo(assistant, District.class);
|
||||
TableInfoHelper.initTableInfo(assistant, DistrictStrategy.class);
|
||||
TableInfoHelper.initTableInfo(assistant, AssetInfo.class);
|
||||
tools = new DistrictStateAdminTools(districtMapper, districtStrategyMapper, assetInfoMapper,
|
||||
m0TransactionManager);
|
||||
User caller = new User();
|
||||
caller.setId(812L);
|
||||
AuthContextHolder.set(new AuthContext(null, caller));
|
||||
lenient().when(m0TransactionManager.getTransaction(any())).thenReturn(transactionStatus);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
AuthContextHolder.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMissingLocator() {
|
||||
ToolCallException e = assertThrows(ToolCallException.class,
|
||||
() -> tools.stateUpdate(null, " ", 1, null, "2026-11-18", null));
|
||||
assertEquals(McpErrorCode.INVALID_ARGUMENT, e.getCode());
|
||||
verify(districtMapper, never()).selectList(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniesServiceTokenWithoutUser() {
|
||||
AuthContextHolder.set(new AuthContext(null, null));
|
||||
ToolCallException e = assertThrows(ToolCallException.class,
|
||||
() -> tools.stateUpdate("站点A", null, 1, null, "2026-11-18", null));
|
||||
assertEquals(McpErrorCode.PERMISSION_DENIED, e.getCode());
|
||||
verify(districtMapper, never()).selectList(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInvalidStateAndMissingOrInvalidDates() {
|
||||
assertInvalid(() -> tools.stateUpdate("站点A", null, 4, null, null, null));
|
||||
assertInvalid(() -> tools.stateUpdate("站点A", null, 0, null, null, null));
|
||||
assertInvalid(() -> tools.stateUpdate("站点A", null, 1, null, "2026-02-30", null));
|
||||
assertInvalid(() -> tools.stateUpdate("站点A", null, 3, null, null, "2026-1-01"));
|
||||
verify(districtMapper, never()).selectList(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAnyDateForDemoState() {
|
||||
assertInvalid(() -> tools.stateUpdate("站点A", null, 2, "", null, null));
|
||||
assertInvalid(() -> tools.stateUpdate("站点A", null, 2, null, "2026-11-18", null));
|
||||
assertInvalid(() -> tools.stateUpdate("站点A", null, 2, null, null, "2026-11-18"));
|
||||
verify(districtMapper, never()).selectList(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateNamesReturnCandidates() {
|
||||
when(districtMapper.selectList(any())).thenReturn(List.of(
|
||||
district(1L, "D-001"), district(2L, "D-002")));
|
||||
|
||||
ToolCallException e = assertThrows(ToolCallException.class,
|
||||
() -> tools.stateUpdate("站点A", null, 1, null, "2026-11-18", null));
|
||||
|
||||
assertEquals(McpErrorCode.INVALID_ARGUMENT, e.getCode());
|
||||
assertTrue(e.getRawMessage().contains("1(D-001)"));
|
||||
assertTrue(e.getRawMessage().contains("2(D-002)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateNumbersAreDataIntegrityError() {
|
||||
when(districtMapper.selectList(any())).thenReturn(List.of(
|
||||
district(1L, "D-001"), district(2L, "D-001")));
|
||||
|
||||
ToolCallException e = assertThrows(ToolCallException.class,
|
||||
() -> tools.stateUpdate(null, "D-001", 1, null, "2026-11-18", null));
|
||||
|
||||
assertEquals(McpErrorCode.DATA_INTEGRITY_ERROR, e.getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingDistrictIsNotFound() {
|
||||
when(districtMapper.selectList(any())).thenReturn(List.of());
|
||||
ToolCallException e = assertThrows(ToolCallException.class,
|
||||
() -> tools.stateUpdate("不存在", null, 1, null, "2026-11-18", null));
|
||||
assertEquals(McpErrorCode.NOT_FOUND_OR_FORBIDDEN, e.getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsDifferentDistrictsFromNameAndNumber() {
|
||||
when(districtMapper.selectList(any()))
|
||||
.thenReturn(List.of(district(1L, "D-001")))
|
||||
.thenReturn(List.of(district(2L, "D-002")));
|
||||
|
||||
ToolCallException e = assertThrows(ToolCallException.class,
|
||||
() -> tools.stateUpdate("站点A", "D-002", 1, null, "2026-11-18", null));
|
||||
|
||||
assertEquals(McpErrorCode.INVALID_ARGUMENT, e.getCode());
|
||||
assertTrue(e.getRawMessage().contains("1(D-001)"));
|
||||
assertTrue(e.getRawMessage().contains("2(D-002)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsMatchingNameAndNumber() {
|
||||
when(districtMapper.selectList(any())).thenReturn(List.of(district(1L, "D-001")));
|
||||
when(districtStrategyMapper.selectOne(any())).thenReturn(strategy(0, null));
|
||||
when(districtStrategyMapper.update(isNull(), any())).thenReturn(1);
|
||||
when(districtMapper.update(isNull(), any())).thenReturn(1);
|
||||
when(assetInfoMapper.update(isNull(), any())).thenReturn(0);
|
||||
|
||||
Map<String, Object> result = tools.stateUpdate("站点A", "D-001", 1,
|
||||
null, "2026-11-18", null);
|
||||
|
||||
assertEquals(1L, result.get("districtId"));
|
||||
verify(districtMapper, org.mockito.Mockito.times(2)).selectList(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsSameStateAndMissingStrategyWithoutWrites() {
|
||||
when(districtMapper.selectList(any())).thenReturn(List.of(district(1L, "D-001")));
|
||||
when(districtStrategyMapper.selectOne(any())).thenReturn(strategy(1, null));
|
||||
|
||||
ToolCallException sameState = assertThrows(ToolCallException.class,
|
||||
() -> tools.stateUpdate("站点A", null, 1, null, "2026-11-18", null));
|
||||
assertEquals(McpErrorCode.INVALID_ARGUMENT, sameState.getCode());
|
||||
assertTrue(sameState.getRawMessage().contains("履约"));
|
||||
|
||||
when(districtStrategyMapper.selectOne(any())).thenReturn(null);
|
||||
ToolCallException missing = assertThrows(ToolCallException.class,
|
||||
() -> tools.stateUpdate("站点A", null, 1, null, "2026-11-18", null));
|
||||
assertEquals(McpErrorCode.DATA_INTEGRITY_ERROR, missing.getCode());
|
||||
verify(districtStrategyMapper, never()).update(isNull(), any());
|
||||
verify(districtMapper, never()).update(isNull(), any());
|
||||
verify(assetInfoMapper, never()).update(isNull(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changesToHonourAndPreservesOtherDateColumns() {
|
||||
stubSuccessfulUpdate(0);
|
||||
DistrictStrategy before = strategy(0, LocalDate.of(2026, 1, 1));
|
||||
before.setHonourDate(LocalDate.of(2025, 12, 1));
|
||||
before.setWeaningDate(LocalDate.of(2025, 12, 31));
|
||||
when(districtStrategyMapper.selectOne(any())).thenReturn(before);
|
||||
when(assetInfoMapper.update(isNull(), any())).thenReturn(2);
|
||||
|
||||
Map<String, Object> result = tools.stateUpdate(" 站点A ", null, 1,
|
||||
"2026-01-02", "2026-11-18", null);
|
||||
|
||||
assertEquals(1L, result.get("districtId"));
|
||||
assertEquals("站点A", result.get("districtName"));
|
||||
assertEquals("D-001", result.get("districtNumber"));
|
||||
assertEquals(2, result.get("linkedAssetCount"));
|
||||
assertNotNull(result.get("requestId"));
|
||||
|
||||
Map<?, ?> beforeResult = (Map<?, ?>) result.get("before");
|
||||
assertEquals(0, beforeResult.get("districtState"));
|
||||
assertEquals("测试", beforeResult.get("districtStateText"));
|
||||
assertEquals("2026-01-01", beforeResult.get("testDate"));
|
||||
Map<?, ?> after = (Map<?, ?>) result.get("after");
|
||||
assertEquals(1, after.get("districtState"));
|
||||
assertEquals("履约", after.get("districtStateText"));
|
||||
assertEquals("2026-01-01", after.get("testDate"));
|
||||
assertEquals("2026-11-18", after.get("honourDate"));
|
||||
assertEquals("2025-12-31", after.get("weaningDate"));
|
||||
|
||||
LambdaUpdateWrapper<DistrictStrategy> strategyUpdate = captureUpdate(districtStrategyMapper);
|
||||
String strategySet = strategyUpdate.getSqlSet();
|
||||
assertTrue(strategySet.contains("district_state"));
|
||||
assertTrue(strategySet.contains("honour_date"));
|
||||
assertTrue(strategySet.contains("modify_id"));
|
||||
assertTrue(strategySet.contains("modify_time"));
|
||||
assertFalse(strategySet.contains("test_date"));
|
||||
assertFalse(strategySet.contains("weaning_date"));
|
||||
|
||||
LambdaUpdateWrapper<District> districtUpdate = captureUpdate(districtMapper);
|
||||
assertTrue(districtUpdate.getSqlSet().contains("modify_id"));
|
||||
assertTrue(districtUpdate.getSqlSet().contains("modify_time"));
|
||||
assertFalse(districtUpdate.getSqlSet().contains("district_name"));
|
||||
|
||||
LambdaUpdateWrapper<AssetInfo> assetUpdate = captureUpdate(assetInfoMapper);
|
||||
String assetSet = assetUpdate.getSqlSet();
|
||||
assertTrue(assetSet.contains("asset_status"));
|
||||
assertTrue(assetSet.contains("modify_id"));
|
||||
assertTrue(assetSet.contains("modify_time"));
|
||||
String assetSql = assetUpdate.getExpression().getNormal().getSqlSegment();
|
||||
assertTrue(assetSql.contains("district_id"));
|
||||
assertTrue(assetSql.contains("soft_delete"));
|
||||
assertTrue(assetSql.contains("asset_status"));
|
||||
verify(m0TransactionManager).commit(transactionStatus);
|
||||
}
|
||||
|
||||
@Test
|
||||
void changesToTestAndDemoMapAssetsToTest() {
|
||||
for (int state : new int[]{0, 2}) {
|
||||
stubSuccessfulUpdate(1);
|
||||
when(districtStrategyMapper.selectOne(any())).thenReturn(strategy(1, LocalDate.of(2026, 1, 1)));
|
||||
when(assetInfoMapper.update(isNull(), any())).thenReturn(1);
|
||||
|
||||
Map<String, Object> result = tools.stateUpdate("站点A", null, state,
|
||||
state == 0 ? "2026-11-18" : null, null, null);
|
||||
|
||||
assertEquals(state, ((Map<?, ?>) result.get("after")).get("districtState"));
|
||||
LambdaUpdateWrapper<AssetInfo> assetUpdate = captureUpdate(assetInfoMapper);
|
||||
assertTrue(assetUpdate.getSqlSet().contains("asset_status"));
|
||||
assertEquals(1, assetUpdate.getParamNameValuePairs().values().stream()
|
||||
.filter(Integer.valueOf(1)::equals).findFirst().orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void weaningDoesNotTouchAssets() {
|
||||
stubSuccessfulUpdate(1);
|
||||
DistrictStrategy before = strategy(1, null);
|
||||
before.setTestDate(LocalDate.of(2026, 1, 1));
|
||||
before.setHonourDate(LocalDate.of(2026, 2, 1));
|
||||
when(districtStrategyMapper.selectOne(any())).thenReturn(before);
|
||||
|
||||
Map<String, Object> result = tools.stateUpdate(null, "D-001", 3,
|
||||
null, null, "2026-11-18");
|
||||
|
||||
assertEquals(0, result.get("linkedAssetCount"));
|
||||
assertEquals("2026-11-18", ((Map<?, ?>) result.get("after")).get("weaningDate"));
|
||||
verify(assetInfoMapper, never()).update(isNull(), any());
|
||||
LambdaUpdateWrapper<DistrictStrategy> strategyUpdate = captureUpdate(districtStrategyMapper);
|
||||
assertFalse(strategyUpdate.getSqlSet().contains("test_date"));
|
||||
assertFalse(strategyUpdate.getSqlSet().contains("honour_date"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void districtUpdateFailureRollsBackM0AndSkipsAssets() {
|
||||
when(districtMapper.selectList(any())).thenReturn(List.of(district(1L, "D-001")));
|
||||
when(districtStrategyMapper.selectOne(any())).thenReturn(strategy(0, null));
|
||||
when(districtStrategyMapper.update(isNull(), any())).thenReturn(1);
|
||||
when(districtMapper.update(isNull(), any())).thenReturn(0);
|
||||
|
||||
ToolCallException e = assertThrows(ToolCallException.class,
|
||||
() -> tools.stateUpdate("站点A", null, 1, null, "2026-11-18", null));
|
||||
|
||||
assertEquals(McpErrorCode.DATA_INTEGRITY_ERROR, e.getCode());
|
||||
verify(m0TransactionManager).rollback(transactionStatus);
|
||||
verify(m0TransactionManager, never()).commit(transactionStatus);
|
||||
verify(assetInfoMapper, never()).update(isNull(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void exposesAdminWriteToolMetadata() throws NoSuchMethodException {
|
||||
Tool tool = DistrictStateAdminTools.class.getMethod("stateUpdate", String.class, String.class,
|
||||
Integer.class, String.class, String.class, String.class).getAnnotation(Tool.class);
|
||||
XqTool xqTool = DistrictStateAdminTools.class.getMethod("stateUpdate", String.class, String.class,
|
||||
Integer.class, String.class, String.class, String.class).getAnnotation(XqTool.class);
|
||||
assertEquals("district.state.update", tool.name());
|
||||
assertEquals("admin", xqTool.category());
|
||||
assertEquals("write", xqTool.kind());
|
||||
}
|
||||
|
||||
private void stubSuccessfulUpdate(int oldState) {
|
||||
when(districtMapper.selectList(any())).thenReturn(List.of(district(1L, "D-001")));
|
||||
when(districtStrategyMapper.selectOne(any())).thenReturn(strategy(oldState, null));
|
||||
when(districtStrategyMapper.update(isNull(), any())).thenReturn(1);
|
||||
when(districtMapper.update(isNull(), any())).thenReturn(1);
|
||||
}
|
||||
|
||||
private void assertInvalid(org.junit.jupiter.api.function.Executable executable) {
|
||||
ToolCallException e = assertThrows(ToolCallException.class, executable);
|
||||
assertEquals(McpErrorCode.INVALID_ARGUMENT, e.getCode());
|
||||
}
|
||||
|
||||
private static District district(long id, String number) {
|
||||
District district = new District();
|
||||
district.setId(id);
|
||||
district.setDistrictName("站点A");
|
||||
district.setDistrictNumber(number);
|
||||
district.setSoftDelete(0);
|
||||
return district;
|
||||
}
|
||||
|
||||
private static DistrictStrategy strategy(int state, LocalDate testDate) {
|
||||
DistrictStrategy strategy = new DistrictStrategy();
|
||||
strategy.setId(99L);
|
||||
strategy.setDistrictId(1L);
|
||||
strategy.setDistrictState(state);
|
||||
strategy.setTestDate(testDate);
|
||||
strategy.setSoftDelete(0);
|
||||
return strategy;
|
||||
}
|
||||
|
||||
private static <T> LambdaUpdateWrapper<T> captureUpdate(
|
||||
com.baomidou.mybatisplus.core.mapper.BaseMapper<T> mapper) {
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<LambdaUpdateWrapper<T>> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
|
||||
verify(mapper, org.mockito.Mockito.atLeastOnce()).update(isNull(), captor.capture());
|
||||
return captor.getValue();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user