feat(mcp): 新增短信验证码提取工具 sms.vercode.latest.query(REQ-20261113-0009)

按手机号提取 m0 sms_send_record 最近一条验证码(buss_type=验证码+soft_delete=0+id DESC
首条),正则提取 4-8 位数字码,send_state 不过滤并配文案,返回 ageSeconds 供判断 90s
redis 有效期。零行级权限,安全模型靠专用 scope 门禁:prod 只绑研发专用 scope 6、dev 只绑
测试专用 scope,显式排除业务 scope(全平台唯一)。王恒拍板 4 决策点全部按建议值执行。
测试:SmsToolsTest 10 例全绿;测试环境冒烟 4/4(有记录提取/无记录 notice/非法入参/
operation scope 拒绝)。
This commit is contained in:
my_local_kimi_dev2
2026-11-13 17:41:41 +08:00
parent f2eb8afcdd
commit 021cee37df
8 changed files with 503 additions and 0 deletions
+1
View File
@@ -105,6 +105,7 @@ xiaoqu-agent-service/
| `repair.handle.list.query` | repair | read | 现场维修记录分页查询(m0 equipment_repair_handle,对齐老 /equipmentRepair/repairRecordHandleList)。入参 id/equipmentRepairId/snCode/agentId/propertyId/districtId/state/userId/assembly/assemblyFault/chipCode(模糊)/accessoryId;硬过滤 soft_delete=0+effective_state=1,固定 id DESC;组件/零部件名按页查 fault_info 字典,chipCode 落 chip_code(修老接口拼不存在列的 bug)。详细设计见 doc/battery-inspection-repair-mcp-design.md |
| `warehouse.order.handler.update` | admin | write | 仓库单据当前待办处理人改派(平台首个写工具,研发/运维专用,REQ-20261107-0002)。入参 orderType(out/in/allocation/transfer)/orderNo/newHandlerMobile 或 newHandlerName(二选一,均 m0 user 精确匹配+soft_delete=0,姓名需唯一命中,同传需一致,REQ-20261107-0004)/memo;UPDATE 流程物理表 schedule_state=1 待办行的 user_id/user_name(并行多行全改派),调拨/划转同步改主表 warehouse_allocation.next_user_name 待办人,出库/入库不动主表,不发消息;无行级权限,只绑"研发专用" scope,服务身份 Token 拒绝。详细设计见 doc/warehouse-order-handler-update-mcp-design.md |
| `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 |
分页统一规范:page 从 1 开始,rows 默认 20、上限 100,超出截断为 100 并在返回 `notice` 字段提示。
@@ -1263,6 +1263,30 @@
---
## 54. sms.vercode.latest.query
短信验证码提取(只读,REQ-20261113-0009),研发/测试专用。
- 分类:admin | 类型:读(readOnlyHint=true)
- 入参:`mobile`(必填,11 位手机号,精确匹配 `user_mobile`)。
- 固定查询口径(王恒拍板):`buss_type='验证码'` + `soft_delete=0` + `id DESC` 首条
(自增 id 等价于 create_time 最新,避免时间精度并列);`send_state` 不过滤,
发送失败记录同样返回并配文案;不做时间窗硬限制。
- 提取规则:`sms_content` 跑正则 `验证码\s*[=::]\s*(\d{4,8})`,命中取第一组;
不命中(历史脏数据/格式漂移)`vercode=null` + 返回原始 `smsContent`,不报错。
- 返回:`record{id, mobile, vercode, smsContent, sendState, sendStateText, bussType,
createTime, ageSeconds}` + `notice`;无记录 `record=null` + notice 提示;
`ageSeconds` 供调用方判断验证码 90 秒 redis 有效期。
- 权限(安全核心):验证码 = 登录绕过原语,零行级权限,访问控制完全靠专用 scope 门禁——
prod 只绑研发专用 scope 6(code=code)、dev 只绑测试专用 scope(code=test),
显式排除业务 scope(prod 1/2/3/5),是全平台唯一显式排除其他所有 scope 的工具;
每次调用落 audit_log。
- 注意:非生产/白名单环境老系统直接返回 123456 且不落库,测试环境查不到记录属正常。
详细设计见 [sms-vercode-latest-mcp-design](sms-vercode-latest-mcp-design.md)。
---
## 附录:在线查看工具清单
```bash
@@ -0,0 +1,124 @@
# 短信验证码提取工具 MCP 设计(REQ-20261113-0009,已批准 2026-11-13)
> **拍板结论(2026-11-13 王恒)**:§7 四个待拍板点全部按建议值执行——
> ① buss_type 固定过滤"验证码";② send_state 不过滤、失败记录也返回并标注;
> ③ 不加时间窗、返回 ageSeconds;④ 工具名 `sms.vercode.latest.query`、category=admin。
> (实现注:kind 按平台惯例为 `read`/`write`,本工具 kind=read,设计稿中"query"为笔误。)
## 1. 背景
研发/测试场景需要"按手机号提取最近一条短信验证码"(自动化登录、联调、测试账号验证)。
老系统没有现成查询接口,目前只能人工查库。本设计新增 1 个只读 MCP 工具。
**敏感性说明**:验证码 = 登录绕过原语。本工具按运维工具口径设计——**零行级权限,
访问控制完全靠专用 scope 门禁**(同 warehouse.order.handler.update 模式),
只绑研发专用/测试专用作用域,**永不绑业务 scope(prod 1/2/3/5)**。
## 2. 数据源调研结论
表:m0 `sms_send_record`(参考库 `beans/b0/SmsSendRecord.java`,m0 mapper)。
| 列 | 说明 |
|---|---|
| user_mobile | 手机号 |
| sms_content | 发送内容,验证码记录为 `验证码=123456` 或 `【小趣智品】验证码=123456` |
| buss_type | 业务类型,验证码记录固定为 `验证码`(SendSmsController.java:84/97、LoginController.java:195/208、AccountController、ChargeController 均同) |
| send_state | 0 成功 / 1 失败(失败记录 content 里也有码,但 redis 未写入,实际不可用) |
| report_state | 验证码记录固定写 99(不过滤) |
| soft_delete | 0 正常 / 99 停用 |
| create_time | 发送时间 |
验证码本体:`RandomUtil.randomNumbers(6)`,6 位数字;redis 有效期 90 秒
(SendSmsController.java:93)。非生产/白名单环境直接返回 123456 且**不落库**,
所以测试环境查不到记录属正常现象。
## 3. 工具定义
| 项 | 值 |
|---|---|
| 工具名 | `sms.vercode.latest.query` |
| category | `admin` |
| kind | `read`(只读) |
| 工具类 | 新建 `SmsTools`(同域后续可加短信记录列表工具) |
| 数据源 | 纯 MySQL m0,无 ES、无 Redis |
| 行级权限 | 无(scope 门禁,见 §6) |
## 4. 参数契约
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| mobile | string | 是 | 11 位手机号,精确匹配 `user_mobile` |
查询口径(固定,全部保老系统写入口径):
- `user_mobile = mobile`
- `buss_type = '验证码'`
- `soft_delete = 0`
- 按 `id DESC` 取第一条(自增 id 等价于 create_time 最新,避免时间精度并列)
提取规则:对 `sms_content` 跑正则 `验证码\s*[=::]\s*(\d{4,8})`,命中取第一组;
不命中(历史脏数据/格式漂移)返回 `vercode=null` + 原始 `smsContent`,不报错。
## 5. 返回契约
统一 ToolResult 结构,`record` 对象:
```json
{
"record": {
"id": 123456789,
"mobile": "13800000000",
"vercode": "483920",
"smsContent": "验证码=483920",
"sendState": 0,
"sendStateText": "发送成功",
"bussType": "验证码",
"createTime": "2026-11-13 17:20:30",
"ageSeconds": 45
},
"notice": null
}
```
- 无记录:`record=null` + `notice="该手机号暂无验证码短信记录"`
- `ageSeconds` = 当前时间 - createTime,供调用方判断 90 秒有效期(工具不做硬过期判断,
失败记录 sendState=1 也照样返回并配文案,由调用方决定可用性——**待拍板点 2**)
- 错误码:`INVALID_ARGUMENT`(手机号为空/非 11 位),`ToolCallException` 透出文案
## 6. scope 绑定(安全核心)
| 环境 | 绑定 | 说明 |
|---|---|---|
| prod | **只绑 scope 6(研发专用,code=code)** | INSERT IGNORE scope_tool(6, tool_id);严禁绑 1/2/3/5 |
| dev | seed-dev 只加「测试专用」scope 绑定 | 不加 operation 等业务 scope |
按 2026-11-07 王恒口径"所有工具默认绑研发专用 scope 6",本工具是唯一**显式排除
其他所有 scope** 的工具(其他查询工具是"默认绑 6",本工具是"只绑 6")。
服务 Token 只有 sync 作用域,天然调不到。
审计:每次调用落 svc audit_log(含调用方 token 身份、入参 mobile、request_id),
与现有工具审计链路一致。
## 7. 待拍板点(建议值)
1. **buss_type 固定过滤"验证码"**(建议)vs 不过滤取任意短信最新一条。
2. **send_state 不过滤**,最新一条即使是发送失败也返回、文案标注(建议——失败记录
同样能反映"系统生成了什么码",联调更有用)vs 只看 send_state=0。
3. **不做时间窗硬限制**,返回 ageSeconds(建议)vs 加 withinMinutes 参数只查近 N 分钟。
4. 工具名 `sms.vercode.latest.query`(建议),category=admin。
## 8. 变更文件清单
- 新增 `entity/m0/SmsSendRecord.java`(本地拷贝,全列对齐参考库——PR #31 教训)
- 新增 `mapper/m0/SmsSendRecordMapper.java`
- 新增 `mcp/tool/SmsTools.java`(1 个工具方法)
- 新增 `SmsToolsTest`(参数校验/提取正则含【小趣智品】前缀格式/空记录/sendState 文案/soft_delete 过滤)
- `sql/seed-dev.sql`:测试专用 scope 绑定
- `README.md` + `doc/agent-mcp-tools-reference.md`:登记
- 装配层零改动(ToolObject 扫描自动注册)
## 9. 测试与上线流程
按 AGENTS.md 标准流程:单测全绿 → `./deploy/test-up.sh` 测试环境冒烟
(scopeCode=test 签 Token;注意 dev 库可能无验证码记录,空记录路径也要验)→
push main → remote-deploy → 确认 ToolSyncService 新增 tool → 绑 prod scope 6 →
生产只读核验(tools/list 可见 + 真实手机号查询)。ai-proj 走自审批闭环。
+8
View File
@@ -107,6 +107,14 @@ SELECT s.id, t.id, 0 FROM agent_scope s JOIN tool t
WHERE s.code = 'test' AND t.kind = 'write'
AND NOT EXISTS (SELECT 1 FROM scope_tool st WHERE st.scope_id = s.id AND st.tool_id = t.id);
-- 短信验证码提取(sms.vercode.latest.query,REQ-20261113-0009):验证码 = 登录敏感原语,
-- 全平台唯一"显式排除业务 scope"的工具——dev 只绑「测试专用」(code='test'),对应 prod 只绑研发专用 scope 6;
-- 不进入 operation/hardware/ops-query/sync 等任何其他作用域。
INSERT INTO scope_tool (scope_id, tool_id, create_id)
SELECT s.id, t.id, 0 FROM agent_scope s JOIN tool t
WHERE s.code = 'test' AND t.name = 'sms.vercode.latest.query'
AND NOT EXISTS (SELECT 1 FROM scope_tool st WHERE st.scope_id = s.id AND st.tool_id = t.id);
COMMIT;
-- 校验
@@ -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;
/** 短信发送记录(m0.sms_send_record),逐字段复制自老系统 publicbeanandmap beans/b0/SmsSendRecord。 */
@Getter
@Setter
@ToString
@TableName("sms_send_record")
public class SmsSendRecord 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;
/** 0 正常,99 停用 */
private Integer softDelete;
/** 手机号 */
private String userMobile;
/** 发送内容(验证码记录形如 "验证码=123456" 或 "【小趣智品】验证码=123456") */
private String smsContent;
/** 短信id */
private String smsid;
/** 0:成功;1:失败 */
private Integer sendState;
/** 0:成功;1:失败(验证码记录固定写 99) */
private Integer reportState;
private String reportValue;
/** 业务类型(验证码记录固定为 "验证码") */
private String bussType;
}
@@ -0,0 +1,7 @@
package me.iiv.agent.mapper.m0;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import me.iiv.agent.entity.m0.SmsSendRecord;
public interface SmsSendRecordMapper extends BaseMapper<SmsSendRecord> {
}
@@ -0,0 +1,129 @@
package me.iiv.agent.mcp.tool;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.iiv.agent.entity.m0.SmsSendRecord;
import me.iiv.agent.mapper.m0.SmsSendRecordMapper;
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 org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 短信验证码提取工具(REQ-20261113-0009,设计文档 doc/sms-vercode-latest-mcp-design.md)。
* 研发/测试专用:按手机号提取 m0 sms_send_record 最近一条验证码(buss_type=验证码、soft_delete=0、
* id DESC 首条),从 sms_content 正则提取数字码。验证码 = 登录绕过原语,零行级权限,
* 访问控制完全靠专用 scope 门禁(prod 只绑研发专用 scope 6,dev 只绑测试专用 scope)。
*/
@Component
public class SmsTools implements ToolObject {
/** 验证码业务类型(老系统写入口径,SendSmsController/LoginController 等均固定写 "验证码") */
private static final String BUSS_TYPE_VERCODE = "验证码";
/** 验证码提取规则:兼容 "验证码=123456" 与 "【小趣智品】验证码=123456",4-8 位数字 */
private static final Pattern VERCODE_PATTERN = Pattern.compile("验证码\\s*[=::]\\s*(\\d{4,8})");
private static final Pattern MOBILE_PATTERN = Pattern.compile("^1\\d{10}$");
final SmsSendRecordMapper smsSendRecordMapper;
public SmsTools(SmsSendRecordMapper smsSendRecordMapper) {
this.smsSendRecordMapper = smsSendRecordMapper;
}
/**
* 提取指定手机号最近一条验证码短信。固定口径:buss_type=验证码 + soft_delete=0 + id DESC 首条;
* send_state 不过滤(发送失败的记录同样返回并标注,由调用方结合 ageSeconds 判断可用性,
* 验证码 redis 有效期 90 秒)。无记录返回 record=null + notice,不报错。
*/
@XqTool(category = "admin", kind = "read")
@Tool(name = "sms.vercode.latest.query", description = "【研发/测试专用】按手机号提取最近一条短信验证码。"
+ "查询 m0 sms_send_record 中该手机号 buss_type=验证码、soft_delete=0 的最新一条记录(id 倒序),"
+ "从发送内容中正则提取 4-8 位数字验证码(兼容 \"验证码=123456\" 与 \"【小趣智品】验证码=123456\" 格式,"
+ "内容格式不命中时 vercode 为 null 并返回原始 smsContent,不报错)。"
+ "send_state 不过滤:发送失败(sendState=1)的记录也返回并配 sendStateText 文案。"
+ "返回 ageSeconds(距发送秒数)供判断验证码 90 秒 redis 有效期,工具本身不做时间窗限制。"
+ "该手机号无验证码记录时 record 为 null 并附 notice。"
+ "注意:验证码是登录敏感原语,本工具零行级权限,仅靠专用 scope 门禁,每次调用落审计日志。")
public Map<String, Object> smsVercodeLatestQuery(
@ToolParam(description = "11 位手机号,精确匹配 user_mobile") String mobile) {
if (!StringUtils.hasText(mobile)) {
throw new ToolCallException(McpErrorCode.INVALID_ARGUMENT, "mobile 不能为空");
}
String trimmedMobile = mobile.trim();
if (!MOBILE_PATTERN.matcher(trimmedMobile).matches()) {
throw new ToolCallException(McpErrorCode.INVALID_ARGUMENT,
"mobile 必须是 11 位手机号: " + trimmedMobile);
}
List<SmsSendRecord> rows = smsSendRecordMapper.selectList(new LambdaQueryWrapper<SmsSendRecord>()
.eq(SmsSendRecord::getUserMobile, trimmedMobile)
.eq(SmsSendRecord::getBussType, BUSS_TYPE_VERCODE)
.eq(SmsSendRecord::getSoftDelete, 0)
.orderByDesc(SmsSendRecord::getId)
.last("LIMIT 1"));
Map<String, Object> result = new LinkedHashMap<>();
if (rows.isEmpty()) {
result.put("record", null);
result.put("notice", "该手机号暂无验证码短信记录");
return result;
}
SmsSendRecord row = rows.get(0);
Map<String, Object> record = new LinkedHashMap<>();
record.put("id", row.getId());
record.put("mobile", row.getUserMobile());
record.put("vercode", extractVercode(row.getSmsContent()));
record.put("smsContent", row.getSmsContent());
record.put("sendState", row.getSendState());
record.put("sendStateText", sendStateText(row.getSendState()));
record.put("bussType", row.getBussType());
record.put("createTime", format(row.getCreateTime()));
record.put("ageSeconds", ageSeconds(row.getCreateTime()));
result.put("record", record);
result.put("notice", null);
return result;
}
/** 从短信内容提取验证码;不命中(历史脏数据/格式漂移)返回 null。 */
static String extractVercode(String smsContent) {
if (smsContent == null) {
return null;
}
Matcher matcher = VERCODE_PATTERN.matcher(smsContent);
return matcher.find() ? matcher.group(1) : null;
}
private static String sendStateText(Integer sendState) {
if (sendState == null) {
return null;
}
return switch (sendState) {
case 0 -> "发送成功";
case 1 -> "发送失败";
default -> "未知(" + sendState + ")";
};
}
private static Long ageSeconds(Date createTime) {
return createTime == null ? null : (System.currentTimeMillis() - createTime.getTime()) / 1000;
}
private static String format(Date value) {
return value == null ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
}
}
@@ -0,0 +1,167 @@
package me.iiv.agent.mcp.tool;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import me.iiv.agent.entity.m0.SmsSendRecord;
import me.iiv.agent.mapper.m0.SmsSendRecordMapper;
import me.iiv.agent.mcp.McpErrorCode;
import me.iiv.agent.mcp.ToolCallException;
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.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
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.assertNotNull;
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.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class SmsToolsTest {
@Mock SmsSendRecordMapper smsSendRecordMapper;
SmsTools tools;
@BeforeEach
void setUp() {
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
TableInfoHelper.initTableInfo(assistant, SmsSendRecord.class);
tools = new SmsTools(smsSendRecordMapper);
}
@Test
void rejectsBlankMobile() {
ToolCallException e = assertThrows(ToolCallException.class,
() -> tools.smsVercodeLatestQuery(" "));
assertEquals(McpErrorCode.INVALID_ARGUMENT, e.getCode());
}
@Test
void rejectsMalformedMobile() {
ToolCallException e1 = assertThrows(ToolCallException.class,
() -> tools.smsVercodeLatestQuery("12345"));
assertEquals(McpErrorCode.INVALID_ARGUMENT, e1.getCode());
ToolCallException e2 = assertThrows(ToolCallException.class,
() -> tools.smsVercodeLatestQuery("23800000000"));
assertEquals(McpErrorCode.INVALID_ARGUMENT, e2.getCode());
assertTrue(e2.getRawMessage().contains("11 位"));
}
@Test
void noRecordReturnsNullWithNotice() {
when(smsSendRecordMapper.selectList(any())).thenReturn(List.of());
Map<String, Object> result = tools.smsVercodeLatestQuery("13800000000");
assertNull(result.get("record"));
assertEquals("该手机号暂无验证码短信记录", result.get("notice"));
}
@Test
void extractsVercodeFromPlainContent() {
when(smsSendRecordMapper.selectList(any()))
.thenReturn(List.of(record(100L, "13800000000", "验证码=483920", 0)));
Map<String, Object> result = tools.smsVercodeLatestQuery("13800000000");
@SuppressWarnings("unchecked")
Map<String, Object> record = (Map<String, Object>) result.get("record");
assertNotNull(record);
assertEquals("483920", record.get("vercode"));
assertEquals("验证码=483920", record.get("smsContent"));
assertEquals(0, record.get("sendState"));
assertEquals("发送成功", record.get("sendStateText"));
assertEquals("验证码", record.get("bussType"));
assertNull(result.get("notice"));
}
@Test
void extractsVercodeFromBrandedContent() {
when(smsSendRecordMapper.selectList(any()))
.thenReturn(List.of(record(101L, "13800000000", "【小趣智品】验证码=123456", 0)));
Map<String, Object> result = tools.smsVercodeLatestQuery("13800000000");
@SuppressWarnings("unchecked")
Map<String, Object> record = (Map<String, Object>) result.get("record");
assertEquals("123456", record.get("vercode"));
}
@Test
void unmatchedContentReturnsNullVercodeWithRawContent() {
when(smsSendRecordMapper.selectList(any()))
.thenReturn(List.of(record(102L, "13800000000", "您的验证码为 abcdef", 0)));
Map<String, Object> result = tools.smsVercodeLatestQuery("13800000000");
@SuppressWarnings("unchecked")
Map<String, Object> record = (Map<String, Object>) result.get("record");
assertNull(record.get("vercode"));
assertEquals("您的验证码为 abcdef", record.get("smsContent"));
}
@Test
void failedSendRecordReturnedWithText() {
when(smsSendRecordMapper.selectList(any()))
.thenReturn(List.of(record(103L, "13800000000", "验证码=654321", 1)));
Map<String, Object> result = tools.smsVercodeLatestQuery("13800000000");
@SuppressWarnings("unchecked")
Map<String, Object> record = (Map<String, Object>) result.get("record");
assertEquals(1, record.get("sendState"));
assertEquals("发送失败", record.get("sendStateText"));
assertEquals("654321", record.get("vercode"));
}
@Test
void ageSecondsReflectsCreateTime() {
SmsSendRecord row = record(104L, "13800000000", "验证码=111111", 0);
row.setCreateTime(new Date(System.currentTimeMillis() - 30_000));
when(smsSendRecordMapper.selectList(any())).thenReturn(List.of(row));
Map<String, Object> result = tools.smsVercodeLatestQuery("13800000000");
@SuppressWarnings("unchecked")
Map<String, Object> record = (Map<String, Object>) result.get("record");
Long ageSeconds = (Long) record.get("ageSeconds");
assertNotNull(ageSeconds);
assertTrue(ageSeconds >= 30 && ageSeconds < 40, "ageSeconds 应约为 30,实际 " + ageSeconds);
assertNotNull(record.get("createTime"));
}
@Test
void queryFiltersByMobileBussTypeAndSoftDelete() {
when(smsSendRecordMapper.selectList(any())).thenReturn(List.of());
tools.smsVercodeLatestQuery("13800000000");
ArgumentCaptor<LambdaQueryWrapper<SmsSendRecord>> captor =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(smsSendRecordMapper).selectList(captor.capture());
String sqlSegment = captor.getValue().getSqlSegment();
assertTrue(sqlSegment.contains("user_mobile"), sqlSegment);
assertTrue(sqlSegment.contains("buss_type"), sqlSegment);
assertTrue(sqlSegment.contains("soft_delete"), sqlSegment);
}
@Test
void extractVercodeEdgeCases() {
assertEquals("1234", SmsTools.extractVercode("验证码:1234"));
assertEquals("12345678", SmsTools.extractVercode("验证码: 12345678"));
assertEquals("123456", SmsTools.extractVercode("验证码 = 123456"));
assertNull(SmsTools.extractVercode(null));
assertNull(SmsTools.extractVercode("验证码=abc"));
}
private static SmsSendRecord record(Long id, String mobile, String content, Integer sendState) {
SmsSendRecord row = new SmsSendRecord();
row.setId(id);
row.setUserMobile(mobile);
row.setSmsContent(content);
row.setSendState(sendState);
row.setBussType("验证码");
row.setSoftDelete(0);
row.setCreateTime(new Date());
return row;
}
}