陈昶聿
9 天以前 e2b0e66b92759eb6a24b0a4e24aa60e76bbdc1a7
feat: 实现妇幼随访按周期发送

- 新增妇幼随访计划、节点、发送日志表及 Mapper

- 支持 followupPeriod JSON 解析,按 plannedFollowTime 基准日排期

- 短信走云MAS,微信走 sendChatLs,独立于普通随访补偿链路

- 增加 1 天补发窗口、过期标记、失败重试及定时任务入口

- 补充功能说明、测试报告和本地库 DDL 实测记录
已修改5个文件
已添加29个文件
3275 ■■■■■ 文件已修改
.gitignore 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/妇幼随访按周期发送功能说明_20261117.md 378 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/妇幼随访按周期发送测试报告_20261117.md 276 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-quartz/src/main/java/com/ruoyi/quartz/task/RyTask.java 36 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/common/MchFollowupConstants.java 79 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/domain/MchFollowupArchiveCandidate.java 20 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/domain/MchFollowupNode.java 32 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/domain/MchFollowupPlan.java 76 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/domain/MchFollowupPlanItem.java 66 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/domain/MchFollowupSendLog.java 33 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/mapper/MchFollowupPlanItemMapper.java 38 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/mapper/MchFollowupPlanMapper.java 32 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/mapper/MchFollowupSendLogMapper.java 13 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/impl/PatChildArchiveServiceImpl.java 17 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/impl/PatMaternityArchiveServiceImpl.java 17 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/impl/PatSpecificArchiveGenerateServiceImpl.java 4 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/mch/IMchFollowupPlanService.java 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/mch/IMchFollowupSendService.java 15 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/mch/MchFollowupDueDecision.java 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/mch/MchFollowupMessageSender.java 133 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/mch/MchFollowupPeriodParser.java 224 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/mch/MchFollowupPlanAssembler.java 46 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/mch/MchFollowupPlanServiceImpl.java 321 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/mch/MchFollowupSendOutcome.java 69 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/mch/MchFollowupSendServiceImpl.java 210 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/mch/MchFollowupSendWindow.java 30 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/java/com/smartor/service/mch/MchFollowupTimeResolver.java 60 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/resources/mapper/smartor/MchFollowupPlanItemMapper.xml 128 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/resources/mapper/smartor/MchFollowupPlanMapper.xml 126 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/main/resources/mapper/smartor/MchFollowupSendLogMapper.xml 15 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/test/java/com/smartor/service/mch/MchFollowupLogicCheck.java 183 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/test/java/com/smartor/service/mch/MchFollowupPlanServiceCheck.java 283 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
smartor/src/test/java/com/smartor/service/mch/MchFollowupSendServiceCheck.java 198 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
sql/mch_followup_plan_20261117.sql 81 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
.gitignore
@@ -37,6 +37,7 @@
!/sql/quartz.sql
!/sql/ry_20220822.sql
!/sql/pat_specific_archive_generate_config_lishui_mch_20261104.sql
!/sql/mch_followup_plan_20261117.sql
sql/_probe/
*.log
_dbcheck.txt
docs/¸¾Ó×Ëæ·Ã°´ÖÜÆÚ·¢Ë͹¦ÄÜ˵Ã÷_20261117.md
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,378 @@
# å¦‡å¹¼éšè®¿æŒ‰å‘¨æœŸå‘送功能说明
> ç‰ˆæœ¬ï¼š2026-11-17
> é€‚用机构:丽水市妇幼保健院 `orgid = 47226079133110211G1001`
> å…³è”模块:`smartor`、`ruoyi-quartz`
> å…³è”表:`mch_followup_plan`、`mch_followup_plan_item`、`mch_followup_send_log`
---
## ä¸€ã€åŠŸèƒ½ç›®æ ‡
妇幼专科档案(妇保/儿保)维护了:
- `plannedFollowTime`:整个随访周期的**基准日**
- `followupPeriod`:JSON æ ¼å¼çš„随访周期,包含发送方式、发送内容、发送天数等
系统按这两个字段生成妇幼专用的发送计划,并在到期时:
- çŸ­ä¿¡ï¼šè°ƒç”¨ä¸­å›½ç§»åŠ¨äº‘MAS `SmsUtils.sendYunMasSms`
- å¾®ä¿¡ï¼šè°ƒç”¨ `SmsUtils.sendChatLs`(即 `/sms/sendChatFuyou` çš„内部实现)
妇幼随访**不进入**普通随访的 `service_subtask_preachform` / `compensateTask` è¡¥å¿é“¾è·¯ï¼Œé¿å…ä¸Žé€šç”¨éšè®¿äº’相影响。
---
## äºŒã€æ—¶é—´å£å¾„
### 2.1 åŸºå‡†æ—¥
`plannedFollowTime` æ˜¯æ•´ä¸ªå‘¨æœŸçš„基准日,所有节点都以它计算:
```text
节点发送时间 = plannedFollowTime çš„æ—¥æœŸ + item.dayOffset å¤© + æ—¶åˆ†ç§’
```
**不是**“上一次发送后顺延”,而是固定从基准日排期。
### 2.2 æ—¶åˆ†ç§’规则
优先级:
1. `item.sendTime` æœ‰å€¼ â†’ ä½¿ç”¨ `item.sendTime`;
2. å¦åˆ™ï¼Œ`plannedFollowTime` çš„æ—¶åˆ†ç§’不是 `00:00:00` â†’ æ²¿ç”¨ `plannedFollowTime` çš„æ—¶åˆ†ç§’ï¼›
3. å¦åˆ™é»˜è®¤ `09:00`。
如果确实需要零点发送,必须显式配置:
```json
{"sendTime": "00:00"}
```
### 2.3 ç¤ºä¾‹
`plannedFollowTime = 2026-11-20 14:30:00`
| dayOffset | sendTime | å®žé™…发送时间 |
|---|---|---|
| 0 | ç©º | 2026-11-20 14:30:00 |
| 3 | ç©º | 2026-11-23 14:30:00 |
| 7 | 09:00 | 2026-11-27 09:00:00 |
`plannedFollowTime = 2026-11-20 00:00:00`
| dayOffset | sendTime | å®žé™…发送时间 |
|---|---|---|
| 0 | ç©º | 2026-11-20 09:00:00 |
| 3 | ç©º | 2026-11-23 09:00:00 |
---
## ä¸‰ã€followupPeriod JSON æ ¼å¼
`followup_period` å·²ç”± `varchar(100)` æ‰©å±•为 `TEXT`。
### 3.1 æ˜¾å¼èŠ‚ç‚¹ï¼ˆæŽ¨èï¼‰
```json
{
  "version": 1,
  "items": [
    {
      "seq": 1,
      "dayOffset": 0,
      "sendTime": "09:00",
      "sendType": "sms",
      "content": "您好${patname},请按计划复诊。"
    },
    {
      "seq": 2,
      "dayOffset": 3,
      "sendTime": "09:00",
      "sendType": "wechat",
      "templateId": 16,
      "titleName": "诊后随访提醒",
      "content": "您好${patname},请按计划复诊。",
      "url": "https://example.com/followup"
    },
    {
      "seq": 3,
      "dayOffset": 7,
      "sendType": "sms",
      "content": "您好${patname},请按时复诊。"
    }
  ]
}
```
字段:
| å­—段 | å¿…å¡« | è¯´æ˜Ž |
|---|---|---|
| `seq` | å¦ | èŠ‚ç‚¹é¡ºåºï¼Œç¼ºçœæŒ‰æ•°ç»„é¡ºåº 1..N |
| `dayOffset` | æ˜¯ | ç›¸å¯¹ `plannedFollowTime` çš„绝对天数,必须 â‰¥ 0 |
| `sendTime` | å¦ | `HH:mm` æˆ– `HH:mm:ss` |
| `sendType` | æ˜¯ | `sms` / `wechat`;兼容 `4` / `5`、`短信` / `公众号` / `微信` |
| `content` | çŸ­ä¿¡å¿…å¡« | çŸ­ä¿¡æ­£æ–‡ï¼›å¾®ä¿¡æ­£æ–‡å¯é€‰ |
| `templateId` | å¦ | å¾®ä¿¡æ¨¡æ¿ ID |
| `titleName` | å¦ | å¾®ä¿¡æ ‡é¢˜ |
| `url` | å¦ | å¾®ä¿¡è·³è½¬åœ°å€ |
短信节点如果 `content` ä¸ºç©ºä¼šè§£æžå¤±è´¥ï¼Œè®¡åˆ’进入“待补充/配置异常”状态。
### 3.2 é—´éš” + æ¬¡æ•°
```json
{
  "intervalDays": 3,
  "count": 4,
  "sendTime": "09:00",
  "sendType": "sms",
  "content": "您好${patname},请按计划复诊。"
}
```
表示:
```text
第1次:基准日 + 0天
第2次:基准日 + 3天
第3次:基准日 + 6天
第4次:基准日 + 9天
```
`count` ç¼ºçœæ—¶å¯ç”¨ `followupCycleTimes` å…œåº•。
### 3.3 days æ•°ç»„
```json
{
  "days": [0, 7, 14],
  "sendType": "sms",
  "content": "您好${patname},请按计划复诊。"
}
```
表示基准日 + 0/7/14 å¤©ã€‚
---
## å››ã€è¡¥å‘窗口
只补发 **1 å¤©å†…**到期的节点:
| æ¡ä»¶ | å¤„理 |
|---|---|
| `send_time > now` | å¾…发送 |
| `now - 24小时 <= send_time <= now` | è¡¥å‘ |
| `send_time < now - 24小时` | æ ‡è®°â€œè¿‡æœŸâ€ï¼Œä¸å†å‘送 |
过期节点状态为 `4`,不会给患者发送过时消息。
---
## äº”、计划状态与节点状态
### 5.1 è®¡åˆ’状态 `mch_followup_plan.plan_status`
| å€¼ | å«ä¹‰ |
|---|---|
| 0 | æœ‰æ•ˆ |
| 1 | å·²å–消(重建时取消旧计划) |
| 2 | å·²å®Œæˆï¼ˆæ— å¾…发送/发送中节点) |
| 3 | å¾…补充/配置异常(拟随访时间为空、JSON éžæ³•等) |
### 5.2 èŠ‚ç‚¹çŠ¶æ€ `mch_followup_plan_item.send_status`
| å€¼ | å«ä¹‰ |
|---|---|
| 0 | å¾…发送 |
| 1 | å‘送中 |
| 2 | æˆåŠŸ |
| 3 | å¤±è´¥ï¼ˆé‡è¯•耗尽) |
| 4 | è¿‡æœŸï¼ˆè¶…过 1 å¤©è¡¥å‘窗口) |
| 5 | å–消 |
| 6 | è·³è¿‡ï¼ˆæ‰‹æœºå·ä¸ºç©ºç­‰ï¼‰ |
---
## å…­ã€æ•´ä½“流程
### 6.1 æ¡£æ¡ˆä¿å­˜åŽè‡ªåŠ¨é‡å»ºè®¡åˆ’
以下入口保存档案后都会调用 `IMchFollowupPlanService.rebuildForArchive`:
- `PatMaternityArchiveServiceImpl.insertOrUpdateMaternityArchive`
- `PatChildArchiveServiceImpl.insertOrUpdateChildArchive`
自动档案生成(门诊接诊完成、住院随访完成)也走这两个 Service,因此同样会触发。
重建规则:
1. åªå¤„理丽水妇幼;
2. `plannedFollowTime` ä¸ºç©º â†’ ç”Ÿæˆâ€œå¾…补充”计划,不生成节点;
3. `followupPeriod` éžæ³• â†’ ç”Ÿæˆâ€œé…ç½®å¼‚常”计划,不生成节点;
4. åŸºå‡†æ—¥/JSON æœªå˜åŒ– â†’ åªåˆ·æ–°è”系人信息,不重复生成节点;
5. åŸºå‡†æ—¥/JSON å˜åŒ– â†’ å–消旧计划中未发送节点,生成新计划和新节点;
6. å·²æˆåŠŸ/已过期/已失败节点保留历史。
### 6.2 å®šæ—¶å‘送
`RyTask.sendMchFollowup()`:
```text
查询 send_status=0
  and send_time <= now
  and (next_retry_time is null or next_retry_time <= now)
  and plan.plan_status=0
  and plan.orgid=丽水妇幼
→ é€æ¡åˆ¤æ–­è¡¥å‘窗口
→ çŸ­ä¿¡/微信发送
→ å†™å‘送日志
→ æ›´æ–°èŠ‚ç‚¹çŠ¶æ€
→ æ— å¾…发送节点时计划置为完成
```
### 6.3 åŽ†å²æ•°æ®è¡¥è®¡åˆ’
`RyTask.generateMchFollowupPlan()`:
```text
扫描已有妇保/儿保档案详情
  planned_follow_time éžç©º
  followup_period éžç©º
→ è¡¥å»ºè®¡åˆ’
```
---
## ä¸ƒã€çŸ­ä¿¡å’Œå¾®ä¿¡å‘送
### 7.1 çŸ­ä¿¡ï¼šäº‘MAS
```java
String configJson = sysConfigService.selectConfigByKey("ls.msg.yunmas", orgid);
SmsUtils.YunMasConfig config = SmsUtils.YunMasConfig.of(configJson);
SmsUtils.SmsResult result = SmsUtils.sendYunMasSms(config, phone, content);
```
成功判定:`result.isOk()`,即 `success=true` ä¸” `rspcod=success`。
短信内容不要手工拼【签名】,云MAS ä¼šæ ¹æ® `sign` ç¼–码自动追加。
### 7.2 å¾®ä¿¡ï¼šsendChatLs
```java
String configJson = sysConfigService.selectConfigByKey("ls.wx.fuyou", orgid);
SmsUtils.LsWxConfig config = SmsUtils.LsWxConfig.of(configJson);
SmsUtils.LsWxMessage message = new SmsUtils.LsWxMessage();
message.setId(templateId);
message.setPatientId(String.valueOf(patid));
message.setPatientName(patname);
message.setIdCard(idcardno);
message.setMobile(phone);
message.setMedCardNo(sourceBizNo);
message.setTitleName(titleName);
message.setContent(content);
message.setUrl(url);
String resp = SmsUtils.sendChatLs(config, message);
```
成功判定:响应 JSON `code == 0`。
`ls.wx.fuyou` æœªé…ç½®æ—¶ï¼Œ`LsWxConfig.of(null)` ä½¿ç”¨å†…置的丽水妇幼默认配置(与 `/sms/sendChatFuyou` ä¸€è‡´ï¼‰ã€‚
---
## å…«ã€é‡è¯•规则
- å•节点失败后最多重试 3 æ¬¡ï¼›
- æ¯æ¬¡é‡è¯•é—´éš” 10 åˆ†é’Ÿï¼›
- é‡è¯•次数达到上限后置为“失败”;
- å¤±è´¥ä¸ä¼šè‡ªåŠ¨åˆ‡æ¢çŸ­ä¿¡/微信通道;
- å¦‚需通道降级,应在 `followupPeriod` ä¸­æ˜¾å¼é…ç½®å¦ä¸€ä¸ªèŠ‚ç‚¹ï¼Œè€Œä¸æ˜¯å¤ç”¨æ™®é€šéšè®¿è¡¥å¿ã€‚
---
## ä¹ã€éƒ¨ç½²æ­¥éª¤
### 9.1 æ‰§è¡Œ SQL
```text
sql/mch_followup_plan_20261117.sql
```
> 2026-11-17 å·²åœ¨æœ¬åœ°/开发库 `smartor_lishui`(MySQL 5.7.34)执行通过;
> æ‰§è¡Œå‰è¡¨ç»“构备份见 `target/ddlcheck/backup-before-20261117.sql`。
包含:
- `followup_period` æ‰©å±•为 `TEXT`;
- `mch_followup_plan`;
- `mch_followup_plan_item`;
- `mch_followup_send_log`。
### 9.2 é…ç½®å®šæ—¶ä»»åŠ¡
在“系统管理 â†’ å®šæ—¶ä»»åŠ¡â€æ–°å¢žï¼š
| ç”¨é€” | è°ƒç”¨ç›®æ ‡ | å»ºè®®é¢‘率 |
|---|---|---|
| åŽ†å²æ¡£æ¡ˆè¡¥è®¡åˆ’ | `ryTask.generateMchFollowupPlan()` | æ¯å¤©ä¸€æ¬¡ |
| å¦‡å¹¼éšè®¿å‘送 | `ryTask.sendMchFollowup()` | æ¯ 5 åˆ†é’Ÿ |
建议只在 `server.port=8095` èŠ‚ç‚¹æ‰§è¡Œï¼Œå¹¶è®¾ç½®â€œç¦æ­¢å¹¶å‘â€ã€‚
### 9.3 é…ç½®å‚æ•°
| é…ç½® key | è¯´æ˜Ž | ç¼ºçœ |
|---|---|---|
| `mch.followup.enabled` | å¦‡å¹¼éšè®¿å¼€å…³ | ç¼ºçœè§†ä¸º `true` |
| `ls.msg.yunmas` | äº‘MAS é…ç½® JSON | ä½¿ç”¨ `SmsUtils` å†…置默认 |
| `ls.wx.fuyou` | ä¸½æ°´å¦‡å¹¼å¾®ä¿¡é…ç½® JSON | ä½¿ç”¨ `SmsUtils` å†…置默认 |
---
## åã€ä»£ç æ¸…单
### æ–°å¢ž
```text
smartor/src/main/java/com/smartor/common/MchFollowupConstants.java
smartor/src/main/java/com/smartor/domain/MchFollowupPlan.java
smartor/src/main/java/com/smartor/domain/MchFollowupPlanItem.java
smartor/src/main/java/com/smartor/domain/MchFollowupSendLog.java
smartor/src/main/java/com/smartor/domain/MchFollowupNode.java
smartor/src/main/java/com/smartor/domain/MchFollowupArchiveCandidate.java
smartor/src/main/java/com/smartor/mapper/MchFollowupPlanMapper.java
smartor/src/main/java/com/smartor/mapper/MchFollowupPlanItemMapper.java
smartor/src/main/java/com/smartor/mapper/MchFollowupSendLogMapper.java
smartor/src/main/java/com/smartor/service/mch/*
smartor/src/main/resources/mapper/smartor/MchFollowupPlanMapper.xml
smartor/src/main/resources/mapper/smartor/MchFollowupPlanItemMapper.xml
smartor/src/main/resources/mapper/smartor/MchFollowupSendLogMapper.xml
sql/mch_followup_plan_20261117.sql
```
### ä¿®æ”¹
```text
PatMaternityArchiveServiceImpl       æ¡£æ¡ˆä¿å­˜åŽé‡å»ºè®¡åˆ’
PatChildArchiveServiceImpl           æ¡£æ¡ˆä¿å­˜åŽé‡å»ºè®¡åˆ’
PatSpecificArchiveGenerateServiceImpl æ¡£æ¡ˆç”Ÿæˆæ—¶å†™å…¥ plannedFollowTime
RyTask                               æ–°å¢ž generateMchFollowupPlan / sendMchFollowup
```
---
## åä¸€ã€æ³¨æ„äº‹é¡¹
1. `plannedFollowTime` å¿…须有值,否则不会自动发送;
2. è‡ªåŠ¨ç”Ÿæˆçš„å¦‡å¹¼æ¡£æ¡ˆä¼šä¼˜å…ˆå– `pat_med_outhosp.fudate` / `pat_med_inhosp.fudate` ä½œä¸º `plannedFollowTime`;
3. è¿‡æœŸèŠ‚ç‚¹ä¸å‘é€ï¼Œåªè¡¥å‘ 1 å¤©å†…节点;
4. å¦‡å¹¼è®¡åˆ’不进入普通随访补偿链路;
5. åªå¯¹ `orgid=47226079133110211G1001` ç”Ÿæ•ˆï¼›
6. å»ºè®®å‘送任务单节点执行,避免重复发送;
7. äº‘MAS/微信配置错误时只影响对应节点,不影响其他节点。
docs/¸¾Ó×Ëæ·Ã°´ÖÜÆÚ·¢ËͲâÊÔ±¨¸æ_20261117.md
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,276 @@
# å¦‡å¹¼éšè®¿æŒ‰å‘¨æœŸå‘送测试报告
> æµ‹è¯•日期:2026-11-17
> æµ‹è¯•模块:`smartor`、`ruoyi-quartz`
> æµ‹è¯•环境:Windows 10 / Git Bash / JDK 21.0.12 / Maven 3.9.9
> æµ‹è¯•方式:纯 main è‡ªæ£€ï¼ˆä¸ä¾èµ– JUnit、Spring å®¹å™¨ã€æ•°æ®åº“、第三方短信/微信接口)
---
## ä¸€ã€æµ‹è¯•结论
| æµ‹è¯•套件 | ç”¨ä¾‹æ•° | é€šè¿‡ | å¤±è´¥ |
|---|---:|---:|---:|
| `MchFollowupLogicCheck` | 40 | 40 | 0 |
| `MchFollowupPlanServiceCheck` | 19 | 19 | 0 |
| `MchFollowupSendServiceCheck` | 18 | 18 | 0 |
| **合计** | **77** | **77** | **0** |
结论:**核心逻辑测试全部通过。**
补充:DDL å·²åœ¨æœ¬åœ°/开发库 `smartor_lishui`(MySQL 5.7.34)实际执行通过,
详见“五、本地数据库 DDL å®žæµ‹â€ã€‚
另外已执行:
```bash
mvn -q -DskipTests compile
mvn -q -pl smartor -am -DskipTests test-compile
```
全模块编译通过,`smartor` æµ‹è¯•代码编译通过。
---
## äºŒã€æµ‹è¯•范围
### 2.1 `MchFollowupLogicCheck`
覆盖:
1. `items` JSON è§£æžï¼›
2. `intervalDays + count` è§£æžï¼›
3. `intervalDays + followupCycleTimes` å…œåº•ï¼›
4. `days` æ•°ç»„解析;
5. éžæ³• JSON、空节点、非法 `sendType`、短信缺 `content`、非法 `sendTime`;
6. åŸºå‡†æ—¥æ—¶é—´è®¡ç®—:
   - `plannedFollowTime` å¸¦æ—¶åˆ†ç§’时沿用;
   - `item.sendTime` è¦†ç›–ï¼›
   - åŸºå‡†æ—¥ `00:00:00` é»˜è®¤ `09:00`;
7. 1 å¤©è¡¥å‘窗口:
   - æœªæ¥èŠ‚ç‚¹å¾…å‘é€ï¼›
   - 1 å°æ—¶å†…补发;
   - æ°å¥½ 24 å°æ—¶è¡¥å‘ï¼›
   - è¶…过 24 å°æ—¶è¿‡æœŸï¼›
8. èŠ‚ç‚¹ç»„è£…ï¼›
9. 3 ä¸ªæ–°å¢ž Mapper XML å¯è§£æžï¼›
10. DDL è„šæœ¬å­˜åœ¨ã€‚
### 2.2 `MchFollowupPlanServiceCheck`
使用动态代理模拟 Mapper å’Œ `ISysConfigService`,覆盖:
1. å¦‡ä¿è®¡åˆ’生成,生成 3 ä¸ªèŠ‚ç‚¹ï¼›
2. èŠ‚ç‚¹æ—¶é—´æŒ‰ `plannedFollowTime + dayOffset` è®¡ç®—ï¼›
3. ç›¸åŒåŸºå‡†æ—¥å’Œå‘¨æœŸæ—¶å¹‚等,不重复生成;
4. `plannedFollowTime` ä¸ºç©ºæ—¶ç”Ÿæˆâ€œå¾…补充”计划,不生成节点;
5. å„¿ä¿æ¡£æ¡ˆä½¿ç”¨ `parentPhone` å…œåº•ï¼›
6. éžä¸½æ°´å¦‡å¹¼æœºæž„不生成计划。
### 2.3 `MchFollowupSendServiceCheck`
使用动态代理模拟 Mapper,并覆写消息发送器,覆盖:
1. çŸ­ä¿¡å‘送成功:
   - èŠ‚ç‚¹çŠ¶æ€ç½®ä¸ºæˆåŠŸï¼›
   - å†™å…¥ç¬¬ä¸‰æ–¹æ¶ˆæ¯ ID;
   - å†™å‘送日志;
   - æ— å¾…发送节点时计划置为完成;
2. è¶…过 1 å¤©èŠ‚ç‚¹ï¼š
   - ä¸è°ƒç”¨ `claimItem`;
   - æ ‡è®°è¿‡æœŸï¼›
   - ä¸å‘送;
3. å¾®ä¿¡å‘送失败:
   - ä¸è®¡æ•°æˆåŠŸï¼›
   - èŠ‚ç‚¹å›žåˆ°å¾…å‘é€ï¼›
   - é‡è¯•次数 +1;
   - ç”Ÿæˆä¸‹æ¬¡é‡è¯•时间。
---
## ä¸‰ã€æ‰§è¡Œå‘½ä»¤
### 3.1 ç¼–译
```bash
mvn -q -DskipTests compile
mvn -q -pl smartor -am -DskipTests test-compile
```
结果:`exitCode=0`。
### 3.2 ç”Ÿæˆä¾èµ– classpath
```bash
mvn -q -pl smartor dependency:build-classpath \
  -Dmdep.outputFile=target/mch-cp.txt
```
### 3.3 æ‰§è¡Œè‡ªæ£€
```bash
CP="smartor/target/classes;smartor/target/test-classes;$(cat smartor/target/mch-cp.txt)"
java -Dfile.encoding=UTF-8 -cp "$CP" \
  com.smartor.service.mch.MchFollowupLogicCheck
java -Dfile.encoding=UTF-8 -cp "$CP" \
  com.smartor.service.mch.MchFollowupPlanServiceCheck
java -Dfile.encoding=UTF-8 -cp "$CP" \
  com.smartor.service.mch.MchFollowupSendServiceCheck
```
### 3.4 ç»“果摘要
```text
MchFollowupLogicCheck        PASS=40,FAIL=0
MchFollowupPlanServiceCheck  PASS=19,FAIL=0
MchFollowupSendServiceCheck  PASS=18,FAIL=0
```
---
## å››ã€é‡ç‚¹éªŒè¯ç»“æžœ
### 4.1 æ—¶é—´è®¡ç®—
| åœºæ™¯ | æœŸæœ› | å®žé™… | ç»“æžœ |
|---|---|---|---|
| åŸºå‡†æ—¥ 14:30,dayOffset=0,无 sendTime | 14:30 | 14:30 | é€šè¿‡ |
| åŸºå‡†æ—¥ 14:30,dayOffset=3,无 sendTime | ç¬¬3天 14:30 | ç¬¬3天 14:30 | é€šè¿‡ |
| dayOffset=7,sendTime=09:00 | ç¬¬7天 09:00 | ç¬¬7天 09:00 | é€šè¿‡ |
| åŸºå‡†æ—¥ 00:00,无 sendTime | 09:00 | 09:00 | é€šè¿‡ |
### 4.2 è¡¥å‘窗口
| åœºæ™¯ | æœŸæœ› | å®žé™… | ç»“æžœ |
|---|---|---|---|
| æœªæ¥èŠ‚ç‚¹ | PENDING | PENDING | é€šè¿‡ |
| 1 å°æ—¶å†…到期 | SEND | SEND | é€šè¿‡ |
| æ°å¥½ 24 å°æ—¶ | SEND | SEND | é€šè¿‡ |
| è¶…过 24 å°æ—¶ | EXPIRED | EXPIRED | é€šè¿‡ |
### 4.3 è®¡åˆ’生成
| åœºæ™¯ | æœŸæœ› | å®žé™… | ç»“æžœ |
|---|---|---|---|
| å¦‡ä¿ 3 èŠ‚ç‚¹ | 3 | 3 | é€šè¿‡ |
| ç›¸åŒåŸºå‡†æ—¥/周期重复调用 | 0 | 0 | é€šè¿‡ |
| æ‹Ÿéšè®¿æ—¶é—´ä¸ºç©º | 0 èŠ‚ç‚¹ï¼Œè®¡åˆ’å¾…è¡¥å…… | ä¸€è‡´ | é€šè¿‡ |
| å„¿ä¿ä½¿ç”¨ parentPhone | 13700000000 | 13700000000 | é€šè¿‡ |
| éžä¸½æ°´å¦‡å¹¼ | 0 | 0 | é€šè¿‡ |
### 4.4 å‘送状态
| åœºæ™¯ | æœŸæœ› | å®žé™… | ç»“æžœ |
|---|---|---|---|
| çŸ­ä¿¡æˆåŠŸ | èŠ‚ç‚¹çŠ¶æ€ 2 | 2 | é€šè¿‡ |
| è¶…过 1 å¤© | èŠ‚ç‚¹çŠ¶æ€ 4 | 4 | é€šè¿‡ |
| å¾®ä¿¡å¤±è´¥ | èŠ‚ç‚¹çŠ¶æ€ 0,重试次数 1 | ä¸€è‡´ | é€šè¿‡ |
---
## äº”、本地数据库 DDL å®žæµ‹
### 5.1 æµ‹è¯•库
使用 `application-druid.yml` å½“前配置的本地/开发库:
```text
database = smartor_lishui
version  = MySQL 5.7.34
```
执行前已自动备份原表结构:
```text
target/ddlcheck/backup-before-20261117.sql
```
### 5.2 æ‰§è¡Œç»“æžœ
执行脚本:
```text
sql/mch_followup_plan_20261117.sql
```
共 6 æ¡ DDL è¯­å¥ï¼Œå…¨éƒ¨æ‰§è¡ŒæˆåŠŸï¼š
| åºå· | è¯­å¥ | ç»“æžœ |
|---|---|---|
| 1 | `pat_maternity_archive_detail.followup_period` â†’ `TEXT` | æˆåŠŸ |
| 2 | `pat_child_archive_detail.followup_period` â†’ `TEXT` | æˆåŠŸ |
| 3 | `pat_specific_archive_generate_config.followup_period` â†’ `TEXT` | æˆåŠŸ |
| 4 | åˆ›å»º `mch_followup_plan` | æˆåŠŸ |
| 5 | åˆ›å»º `mch_followup_plan_item` | æˆåŠŸ |
| 6 | åˆ›å»º `mch_followup_send_log` | æˆåŠŸ |
### 5.3 éªŒè¯ç»“æžœ
| éªŒè¯é¡¹ | ç»“æžœ |
|---|---|
| 3 ä¸ª `followup_period` å­—段类型均为 `TEXT` | é€šè¿‡ |
| `mch_followup_plan` å­˜åœ¨ | é€šè¿‡ |
| `mch_followup_plan_item` å­˜åœ¨ | é€šè¿‡ |
| `mch_followup_send_log` å­˜åœ¨ | é€šè¿‡ |
| å”¯ä¸€ç´¢å¼• `uk_mch_plan_seq` å­˜åœ¨ | é€šè¿‡ |
| è®¡åˆ’ + èŠ‚ç‚¹ + æ—¥å¿— DML å†™å…¥/关联查询 | é€šè¿‡ |
| DML äº‹åŠ¡å›žæ»š | é€šè¿‡ |
| æµ‹è¯•数据清理后三张新表行数 | `0 / 0 / 0` |
### 5.4 åŽŸè¡¨æ•°æ®æ£€æŸ¥
执行前后统计一致:
```text
pat_maternity_archive_detail           rows=4, max_followup_period_len=110
pat_child_archive_detail               rows=3, max_followup_period_len=0
pat_specific_archive_generate_config   rows=1, max_followup_period_len=2
```
说明:
- æœ¬æ¬¡æµ‹è¯•库中 `followup_period` åŽŸæœ¬å·²ç»æ˜¯ `TEXT`,`MODIFY COLUMN` ä¸ºå¹‚等操作;
- å…¶ä»–仍为 `varchar(100)` çš„环境执行脚本时会正常扩展为 `TEXT`;
- æµ‹è¯•数据已回滚/清理,新表为空。
---
## å…­ã€æœªè¦†ç›–项
以下内容未在本次自动化测试中覆盖,需要在测试环境补充验证:
1. **MyBatis XML ä¸ŽçœŸå®žæ•°æ®åº“çš„ SQL å…¼å®¹æ€§**
   å·²æ‰§è¡Œ DDL å’Œ JDBC DML,但未通过 MyBatis æ‰§è¡Œ `selectDueItems`、`selectCandidates`、`updateSendResult` ç­‰ SQL。
   å·²åš XML å¯è§£æžæ€§æ£€æŸ¥ï¼Œä½†æœªè¿žæŽ¥æ•°æ®åº“执行 `selectDueItems`、`selectCandidates`、`updateSendResult` ç­‰ SQL。
3. **真实云MAS短信发送**
   æœªè°ƒç”¨çœŸå®žäº‘MAS接口,避免产生真实短信费用和患者打扰。
4. **真实丽水妇幼微信发送**
   æœªè°ƒç”¨çœŸå®ž `sendChatLs` æŽ¥å£ï¼Œé¿å…å‘真实患者发送消息。
5. **Spring å®¹å™¨å¯åŠ¨éªŒè¯**
   æœªå¯åŠ¨å®Œæ•´ `ruoyi-admin`,建议在测试环境启动后确认:
   - `IMchFollowupPlanService` / `IMchFollowupSendService` æ³¨å…¥æ­£å¸¸ï¼›
   - `RyTask` èƒ½è°ƒç”¨æ–°ä»»åŠ¡ï¼›
   - æ¡£æ¡ˆä¿å­˜åŽè®¡åˆ’表有数据。
6. **多节点并发发送**
   å½“前发送任务未加分布式锁,生产环境建议只在 8095 èŠ‚ç‚¹æ‰§è¡Œï¼Œå¹¶è®¾ç½®â€œç¦æ­¢å¹¶å‘â€ã€‚
---
## ä¸ƒã€é£Žé™©ä¸Žå»ºè®®
1. `followup_period` åœ¨éƒ¨åˆ†çŽ¯å¢ƒä»ä¸º `varchar(100)`,必须执行 DDL æ‰©å±•为 `TEXT`,否则包含发送内容的 JSON ä¼šè¢«æˆªæ–­ï¼›æœ¬æ¬¡ `smartor_lishui` æµ‹è¯•库原本已是 `TEXT`,脚本幂等执行成功。
2. è‡ªåŠ¨ç”Ÿæˆå¦‡å¹¼æ¡£æ¡ˆæ—¶ï¼Œ`plannedFollowTime` ä¼˜å…ˆå– `pat_med_outhosp.fudate` / `pat_med_inhosp.fudate`;如果 HIS æ²¡ç»™éšè®¿æ—¥æœŸï¼Œè®¡åˆ’会进入“待补充”状态。
3. è¿‡æœŸèŠ‚ç‚¹åªæ ‡è®°ä¸å‘é€ï¼Œç¬¦åˆâ€œåªè¡¥å‘ 1 å¤©å†…”的业务口径。
4. äº‘MAS/微信配置错误只影响对应节点,不会阻断计划生成。
5. å»ºè®®ä¸Šçº¿å‰ç”¨ä¸€æ¡æµ‹è¯•档案完整走一遍:
   - æ¡£æ¡ˆä¿å­˜ â†’ è®¡åˆ’生成;
   - ä¿®æ”¹ `plannedFollowTime` â†’ æ—§èŠ‚ç‚¹å–æ¶ˆã€æ–°èŠ‚ç‚¹ç”Ÿæˆï¼›
   - åˆ°æœŸèŠ‚ç‚¹ â†’ çŸ­ä¿¡/微信发送;
   - è¶…过 1 å¤©èŠ‚ç‚¹ â†’ æ ‡è®°è¿‡æœŸã€‚
ruoyi-quartz/src/main/java/com/ruoyi/quartz/task/RyTask.java
@@ -38,6 +38,8 @@
import com.ruoyi.task.domain.VO.ServiceSubtaskDetailTraceVO;
import com.smartor.mapper.*;
import com.smartor.service.*;
import com.smartor.service.mch.IMchFollowupPlanService;
import com.smartor.service.mch.IMchFollowupSendService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
@@ -150,6 +152,12 @@
    @Autowired
    private IPatSpecificArchiveGenerateService patSpecificArchiveGenerateService;
    @Autowired
    private IMchFollowupPlanService mchFollowupPlanService;
    @Autowired
    private IMchFollowupSendService mchFollowupSendService;
    @Autowired
    private com.ruoyi.task.event.FollowupCompletedEventPublisher followupCompletedEventPublisher;
@@ -2373,4 +2381,32 @@
        }
    }
    /**
     * å¦‡å¹¼éšè®¿ï¼šä¸ºå·²æœ‰å¦‡å¹¼æ¡£æ¡ˆè¡¥å»ºè®¡åˆ’。
     *
     * <p>档案新增/修改时会自动重建计划;本任务用于历史数据补建和异常补偿。</p>
     */
    public void generateMchFollowupPlan() {
        try {
            int generated = mchFollowupPlanService.rebuildAll(200);
            log.info("【generateMchFollowupPlan】妇幼随访计划补建完成,生成节点数={}", generated);
        } catch (Exception e) {
            log.error("【generateMchFollowupPlan】妇幼随访计划补建失败", e);
        }
    }
    /**
     * å¦‡å¹¼éšè®¿ï¼šæ‰«æåˆ°æœŸèŠ‚ç‚¹å¹¶å‘é€ã€‚
     *
     * <p>只补发 1 å¤©å†…到期的节点;超过 1 å¤©æ ‡è®°è¿‡æœŸã€‚短信走云MAS,微信走 sendChatLs。</p>
     */
    public void sendMchFollowup() {
        try {
            int sent = mchFollowupSendService.sendDue(200);
            log.info("【sendMchFollowup】妇幼随访发送完成,成功数量={}", sent);
        } catch (Exception e) {
            log.error("【sendMchFollowup】妇幼随访发送失败", e);
        }
    }
}
smartor/src/main/java/com/smartor/common/MchFollowupConstants.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,79 @@
package com.smartor.common;
/**
 * å¦‡å¹¼éšè®¿è®¡åˆ’相关常量。
 *
 * <p>妇幼随访只适用于丽水市妇幼保健院,且使用独立的计划表和发送任务,
 * ä¸è¿›å…¥æ™®é€šéšè®¿çš„ {@code service_subtask_preachform} / {@code compensateTask} è¡¥å¿é“¾è·¯ã€‚</p>
 */
public final class MchFollowupConstants {
    /** æ¡£æ¡ˆç±»åž‹ï¼šå¦‡ä¿ */
    public static final String ARCHIVE_TYPE_MATERNITY = "1";
    /** æ¡£æ¡ˆç±»åž‹ï¼šå„¿ä¿ */
    public static final String ARCHIVE_TYPE_CHILD = "2";
    /** è®¡åˆ’状态:有效 */
    public static final String PLAN_STATUS_ACTIVE = "0";
    /** è®¡åˆ’状态:已取消 */
    public static final String PLAN_STATUS_CANCELED = "1";
    /** è®¡åˆ’状态:已完成 */
    public static final String PLAN_STATUS_COMPLETED = "2";
    /** è®¡åˆ’状态:待补充基准日/配置异常 */
    public static final String PLAN_STATUS_WAITING = "3";
    /** èŠ‚ç‚¹çŠ¶æ€ï¼šå¾…å‘é€ */
    public static final String ITEM_STATUS_PENDING = "0";
    /** èŠ‚ç‚¹çŠ¶æ€ï¼šå‘é€ä¸­ */
    public static final String ITEM_STATUS_SENDING = "1";
    /** èŠ‚ç‚¹çŠ¶æ€ï¼šæˆåŠŸ */
    public static final String ITEM_STATUS_SUCCESS = "2";
    /** èŠ‚ç‚¹çŠ¶æ€ï¼šå¤±è´¥ï¼ˆé‡è¯•è€—å°½ï¼‰ */
    public static final String ITEM_STATUS_FAILED = "3";
    /** èŠ‚ç‚¹çŠ¶æ€ï¼šè¿‡æœŸï¼ˆè¶…è¿‡è¡¥å‘çª—å£ï¼Œæœªå‘é€ï¼‰ */
    public static final String ITEM_STATUS_EXPIRED = "4";
    /** èŠ‚ç‚¹çŠ¶æ€ï¼šå–æ¶ˆ */
    public static final String ITEM_STATUS_CANCELED = "5";
    /** èŠ‚ç‚¹çŠ¶æ€ï¼šè·³è¿‡ï¼ˆæ‰‹æœºå·ä¸ºç©ºç­‰ï¼‰ */
    public static final String ITEM_STATUS_SKIPPED = "6";
    /** å‘送方式:短信 */
    public static final String SEND_TYPE_SMS = "sms";
    /** å‘送方式:微信公众号 */
    public static final String SEND_TYPE_WECHAT = "wechat";
    /** è¡¥å‘窗口:只补发 1 å¤©å†…到期的节点。 */
    public static final long CATCHUP_MILLIS = 24L * 60L * 60L * 1000L;
    /** é»˜è®¤æœ€å¤§é‡è¯•次数。 */
    public static final int DEFAULT_MAX_RETRY = 3;
    /** é»˜è®¤é‡è¯•间隔(分钟)。 */
    public static final int DEFAULT_RETRY_DELAY_MINUTES = 10;
    /** å•次扫描默认上限。 */
    public static final int DEFAULT_BATCH_SIZE = 200;
    /** å¯ç”¨å¼€å…³ï¼ˆsys_config,按机构读取;缺省视为启用)。 */
    public static final String CONFIG_ENABLED = "mch.followup.enabled";
    /** äº‘MAS çŸ­ä¿¡é…ç½®ï¼ˆsys_config,按机构读取)。 */
    public static final String CONFIG_YUNMAS = "ls.msg.yunmas";
    /** ä¸½æ°´å¦‡å¹¼å¾®ä¿¡é…ç½®ï¼ˆsys_config,按机构读取;为空时使用 SmsUtils å†…置默认配置)。 */
    public static final String CONFIG_LS_WX = "ls.wx.fuyou";
    private MchFollowupConstants() {
    }
}
smartor/src/main/java/com/smartor/domain/MchFollowupArchiveCandidate.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,20 @@
package com.smartor.domain;
import lombok.Data;
import java.io.Serializable;
/**
 * å¦‡å¹¼éšè®¿è¡¥è®¡åˆ’扫描候选。
 */
@Data
public class MchFollowupArchiveCandidate implements Serializable {
    private static final long serialVersionUID = 1L;
    private String archiveType;
    private Long archiveId;
    private Long archiveDetailId;
}
smartor/src/main/java/com/smartor/domain/MchFollowupNode.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,32 @@
package com.smartor.domain;
import lombok.Data;
import java.io.Serializable;
/**
 * followupPeriod JSON è§£æžåŽçš„发送节点定义(尚未计算绝对发送时间)。
 */
@Data
public class MchFollowupNode implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer seq;
    private Integer dayOffset;
    /** HH:mm æˆ– HH:mm:ss,可为空 */
    private String sendTime;
    /** sms / wechat */
    private String sendType;
    private String content;
    private String titleName;
    private Long templateId;
    private String url;
}
smartor/src/main/java/com/smartor/domain/MchFollowupPlan.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,76 @@
package com.smartor.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
 * å¦‡å¹¼éšè®¿è®¡åˆ’主表 mch_followup_plan。
 *
 * <p>一个档案详情对应一条有效计划;计划下挂多个发送节点。
 * plannedFollowTime æ˜¯æ•´ä¸ªå‘¨æœŸçš„基准日,节点发送时间 = åŸºå‡†æ—¥ + dayOffset。</p>
 */
@Data
@ApiModel(value = "妇幼随访计划")
public class MchFollowupPlan implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    @ApiModelProperty(value = "机构ID")
    private String orgid;
    @ApiModelProperty(value = "院区ID")
    private String campusid;
    @ApiModelProperty(value = "档案类型:1妇保 2儿保")
    private String archiveType;
    @ApiModelProperty(value = "档案主表ID")
    private Long archiveId;
    @ApiModelProperty(value = "档案详情ID")
    private Long archiveDetailId;
    @ApiModelProperty(value = "来源类型:1门诊 2住院随访 3手工")
    private String sourceType;
    @ApiModelProperty(value = "来源业务编号:门诊号/住院号")
    private String sourceBizNo;
    @ApiModelProperty(value = "患者ID")
    private Long patid;
    @ApiModelProperty(value = "患者姓名")
    private String patname;
    @ApiModelProperty(value = "联系电话")
    private String phone;
    @ApiModelProperty(value = "证件号码")
    private String idcardno;
    @ApiModelProperty(value = "周期基准日")
    private Date plannedFollowTime;
    @ApiModelProperty(value = "随访周期 JSON å¿«ç…§")
    private String followupPeriod;
    @ApiModelProperty(value = "计划状态:0有效 1取消 2完成 3待补充/配置异常")
    private String planStatus;
    @ApiModelProperty(value = "备注")
    private String remark;
    private Date createTime;
    private Date updateTime;
    @ApiModelProperty(value = "发送节点(非表字段)")
    private List<MchFollowupPlanItem> items;
}
smartor/src/main/java/com/smartor/domain/MchFollowupPlanItem.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,66 @@
package com.smartor.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
 * å¦‡å¹¼éšè®¿è®¡åˆ’发送节点 mch_followup_plan_item。
 */
@Data
@ApiModel(value = "妇幼随访计划发送节点")
public class MchFollowupPlanItem implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    @ApiModelProperty(value = "计划ID")
    private Long planId;
    @ApiModelProperty(value = "节点顺序")
    private Integer seq;
    @ApiModelProperty(value = "发送方式:sms/wechat")
    private String sendType;
    @ApiModelProperty(value = "发送时间")
    private Date sendTime;
    @ApiModelProperty(value = "微信标题")
    private String titleName;
    @ApiModelProperty(value = "发送内容")
    private String content;
    @ApiModelProperty(value = "微信模板ID")
    private Long templateId;
    @ApiModelProperty(value = "微信跳转地址")
    private String url;
    @ApiModelProperty(value = "发送状态:0待发送 1发送中 2成功 3失败 4过期 5取消 6跳过")
    private String sendStatus;
    @ApiModelProperty(value = "已重试次数")
    private Integer retryCount;
    @ApiModelProperty(value = "下次重试时间")
    private Date nextRetryTime;
    @ApiModelProperty(value = "实际发送时间")
    private Date sendTimeActual;
    @ApiModelProperty(value = "结果说明")
    private String resultMsg;
    @ApiModelProperty(value = "第三方消息ID")
    private String providerMsgId;
    private Date createTime;
    private Date updateTime;
}
smartor/src/main/java/com/smartor/domain/MchFollowupSendLog.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,33 @@
package com.smartor.domain;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
 * å¦‡å¹¼éšè®¿å‘送日志 mch_followup_send_log。
 */
@Data
public class MchFollowupSendLog implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private Long planId;
    private Long itemId;
    private String sendType;
    private String requestBody;
    private String responseBody;
    private String sendStatus;
    private String resultMsg;
    private Date createTime;
}
smartor/src/main/java/com/smartor/mapper/MchFollowupPlanItemMapper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,38 @@
package com.smartor.mapper;
import com.smartor.domain.MchFollowupPlanItem;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
/**
 * å¦‡å¹¼éšè®¿è®¡åˆ’节点 Mapper。
 */
@Mapper
public interface MchFollowupPlanItemMapper {
    int insertMchFollowupPlanItem(MchFollowupPlanItem item);
    int updateMchFollowupPlanItem(MchFollowupPlanItem item);
    int updateSendResult(MchFollowupPlanItem item);
    MchFollowupPlanItem selectMchFollowupPlanItemById(@Param("id") Long id);
    List<MchFollowupPlanItem> selectByPlanId(@Param("planId") Long planId);
    /**
     * æŸ¥è¯¢åˆ°æœŸèŠ‚ç‚¹ï¼šè®¡åˆ’æœ‰æ•ˆã€æœºæž„ä¸ºä¸½æ°´å¦‡å¹¼ã€å¾…å‘é€ã€åˆ°è¾¾å‘é€æ—¶é—´ã€ä¸”ä¸åœ¨é‡è¯•ç­‰å¾…ä¸­ã€‚
     */
    List<MchFollowupPlanItem> selectDueItems(@Param("orgid") String orgid,
                                             @Param("now") Date now,
                                             @Param("limit") int limit);
    int claimItem(@Param("id") Long id, @Param("now") Date now);
    int cancelPendingByPlanId(@Param("planId") Long planId, @Param("now") Date now);
    int countPendingByPlanId(@Param("planId") Long planId);
}
smartor/src/main/java/com/smartor/mapper/MchFollowupPlanMapper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,32 @@
package com.smartor.mapper;
import com.smartor.domain.MchFollowupArchiveCandidate;
import com.smartor.domain.MchFollowupPlan;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
 * å¦‡å¹¼éšè®¿è®¡åˆ’主表 Mapper。
 */
@Mapper
public interface MchFollowupPlanMapper {
    int insertMchFollowupPlan(MchFollowupPlan plan);
    int updateMchFollowupPlan(MchFollowupPlan plan);
    MchFollowupPlan selectMchFollowupPlanById(@Param("id") Long id);
    List<MchFollowupPlan> selectActiveByArchive(@Param("archiveType") String archiveType,
                                                @Param("archiveId") Long archiveId,
                                                @Param("archiveDetailId") Long archiveDetailId);
    int cancelById(@Param("id") Long id, @Param("updateTime") java.util.Date updateTime);
    int completeById(@Param("id") Long id, @Param("updateTime") java.util.Date updateTime);
    List<MchFollowupArchiveCandidate> selectCandidates(@Param("orgid") String orgid,
                                                       @Param("limit") int limit);
}
smartor/src/main/java/com/smartor/mapper/MchFollowupSendLogMapper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,13 @@
package com.smartor.mapper;
import com.smartor.domain.MchFollowupSendLog;
import org.apache.ibatis.annotations.Mapper;
/**
 * å¦‡å¹¼éšè®¿å‘送日志 Mapper。
 */
@Mapper
public interface MchFollowupSendLogMapper {
    int insertMchFollowupSendLog(MchFollowupSendLog log);
}
smartor/src/main/java/com/smartor/service/impl/PatChildArchiveServiceImpl.java
@@ -6,9 +6,11 @@
import com.ruoyi.common.utils.StringUtils;
import com.smartor.domain.PatChildArchive;
import com.smartor.domain.PatChildArchiveDetail;
import com.smartor.common.MchFollowupConstants;
import com.smartor.mapper.PatChildArchiveMapper;
import com.smartor.service.IPatChildArchiveDetailService;
import com.smartor.service.IPatChildArchiveService;
import com.smartor.service.mch.IMchFollowupPlanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
@@ -32,6 +34,9 @@
    @Autowired
    private IPatChildArchiveDetailService patChildArchiveDetailService;
    @Autowired
    private IMchFollowupPlanService mchFollowupPlanService;
    @Override
    public PatChildArchive selectPatChildArchiveById(Long id)
@@ -191,6 +196,18 @@
            patChildArchiveDetailService.insertPatChildArchiveDetail(patChildArchiveDetail);
        }
        // å¦‡å¹¼éšè®¿è®¡åˆ’:档案新增/修改后按 plannedFollowTime + followupPeriod é‡å»º
        try {
            if (mchFollowupPlanService != null) {
                mchFollowupPlanService.rebuildForArchive(
                        MchFollowupConstants.ARCHIVE_TYPE_CHILD,
                        patChildArchive.getId(), patChildArchiveDetail.getId());
            }
        } catch (Exception e) {
            log.error("妇幼随访计划重建失败,archiveId={},detailId={}",
                    patChildArchive.getId(), patChildArchiveDetail.getId(), e);
        }
        log.info("insertOrUpdateChildArchive处理完成,主表id:{},详情id:{}", patChildArchive.getId(), patChildArchiveDetail.getId());
        return patChildArchive.getId().intValue();
    }
smartor/src/main/java/com/smartor/service/impl/PatMaternityArchiveServiceImpl.java
@@ -8,10 +8,12 @@
import com.smartor.domain.PatChildArchiveDetail;
import com.smartor.domain.PatMaternityArchive;
import com.smartor.domain.PatMaternityArchiveDetail;
import com.smartor.common.MchFollowupConstants;
import com.smartor.mapper.PatMaternityArchiveDetailMapper;
import com.smartor.mapper.PatMaternityArchiveMapper;
import com.smartor.service.IPatMaternityArchiveDetailService;
import com.smartor.service.IPatMaternityArchiveService;
import com.smartor.service.mch.IMchFollowupPlanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
@@ -37,6 +39,9 @@
    private IPatMaternityArchiveDetailService patMaternityArchiveDetailService;
    @Autowired
    private PatMaternityArchiveDetailMapper patMaternityArchiveDetailMapper;
    @Autowired
    private IMchFollowupPlanService mchFollowupPlanService;
    @Override
    public PatMaternityArchive selectPatMaternityArchiveById(Long id)
@@ -215,6 +220,18 @@
            patMaternityArchiveDetailService.insertPatMaternityArchiveDetail(patMaternityArchiveDetail);
        }
        // å¦‡å¹¼éšè®¿è®¡åˆ’:档案新增/修改后按 plannedFollowTime + followupPeriod é‡å»º
        try {
            if (mchFollowupPlanService != null) {
                mchFollowupPlanService.rebuildForArchive(
                        MchFollowupConstants.ARCHIVE_TYPE_MATERNITY,
                        patMaternityArchive.getId(), patMaternityArchiveDetail.getId());
            }
        } catch (Exception e) {
            log.error("妇幼随访计划重建失败,archiveId={},detailId={}",
                    patMaternityArchive.getId(), patMaternityArchiveDetail.getId(), e);
        }
        log.info("insertOrUpdateMaternityArchive处理完成,主表id:{},详情id:{}", patMaternityArchive.getId(), patMaternityArchiveDetail.getId());
        return patMaternityArchive.getId().intValue();
    }
smartor/src/main/java/com/smartor/service/impl/PatSpecificArchiveGenerateServiceImpl.java
@@ -489,6 +489,7 @@
        PatMaternityArchiveDetail detail = new PatMaternityArchiveDetail();
        detail.setArchiveType(config.getArchiveType());
        detail.setFollowupPeriod(config.getFollowupPeriod());
        detail.setPlannedFollowTime(patMedOuthosp.getFudate());
        detail.setSourceType(SpecificArchiveConstants.SOURCE_TYPE_OUTHOSP);
        detail.setSourceBizId(patMedOuthosp.getId());
        detail.setSourceBizNo(patMedOuthosp.getOuthospno());
@@ -504,6 +505,7 @@
        PatChildArchiveDetail detail = new PatChildArchiveDetail();
        detail.setArchiveType(config.getArchiveType());
        detail.setFollowupPeriod(config.getFollowupPeriod());
        detail.setPlannedFollowTime(patMedOuthosp.getFudate());
        detail.setSourceType(SpecificArchiveConstants.SOURCE_TYPE_OUTHOSP);
        detail.setSourceBizId(patMedOuthosp.getId());
        detail.setSourceBizNo(patMedOuthosp.getOuthospno());
@@ -527,6 +529,7 @@
        PatMaternityArchiveDetail detail = new PatMaternityArchiveDetail();
        detail.setArchiveType(config.getArchiveType());
        detail.setFollowupPeriod(config.getFollowupPeriod());
        detail.setPlannedFollowTime(context.inhosp == null ? null : context.inhosp.getFudate());
        detail.setSourceType(SpecificArchiveConstants.SOURCE_TYPE_INHOSP_FOLLOWUP);
        detail.setSourceBizId(inInhospid(context));
        detail.setSourceBizNo(inInhospno(context));
@@ -574,6 +577,7 @@
        PatChildArchiveDetail detail = new PatChildArchiveDetail();
        detail.setArchiveType(config.getArchiveType());
        detail.setFollowupPeriod(config.getFollowupPeriod());
        detail.setPlannedFollowTime(context.inhosp == null ? null : context.inhosp.getFudate());
        detail.setSourceType(SpecificArchiveConstants.SOURCE_TYPE_INHOSP_FOLLOWUP);
        detail.setSourceBizId(inInhospid(context));
        detail.setSourceBizNo(inInhospno(context));
smartor/src/main/java/com/smartor/service/mch/IMchFollowupPlanService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,25 @@
package com.smartor.service.mch;
/**
 * å¦‡å¹¼éšè®¿è®¡åˆ’服务。
 */
public interface IMchFollowupPlanService {
    /**
     * æ ¹æ®æ¡£æ¡ˆè¯¦æƒ…重建妇幼随访计划。
     *
     * @param archiveType     1妇保 2儿保
     * @param archiveId       æ¡£æ¡ˆä¸»è¡¨ID
     * @param archiveDetailId æ¡£æ¡ˆè¯¦æƒ…ID
     * @return æ–°ç”Ÿæˆçš„发送节点数量
     */
    int rebuildForArchive(String archiveType, Long archiveId, Long archiveDetailId);
    /**
     * è¡¥å¿æ‰«æï¼šä¸ºå·²æœ‰å¦‡å¹¼æ¡£æ¡ˆè¡¥å»ºè®¡åˆ’。
     *
     * @param limit å•次扫描上限
     * @return æ–°ç”Ÿæˆçš„发送节点数量
     */
    int rebuildAll(int limit);
}
smartor/src/main/java/com/smartor/service/mch/IMchFollowupSendService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,15 @@
package com.smartor.service.mch;
/**
 * å¦‡å¹¼éšè®¿å‘送服务。
 */
public interface IMchFollowupSendService {
    /**
     * æ‰«æå¹¶å‘送到期节点。
     *
     * @param limit å•次处理上限
     * @return æœ¬æ¬¡å®žé™…发送成功数量
     */
    int sendDue(int limit);
}
smartor/src/main/java/com/smartor/service/mch/MchFollowupDueDecision.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,10 @@
package com.smartor.service.mch;
/**
 * å¦‡å¹¼éšè®¿åˆ°æœŸåˆ¤æ–­ç»“果。
 */
public enum MchFollowupDueDecision {
    PENDING,
    SEND,
    EXPIRED
}
smartor/src/main/java/com/smartor/service/mch/MchFollowupMessageSender.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,133 @@
package com.smartor.service.mch;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sms.SmsUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.smartor.common.MchFollowupConstants;
import com.smartor.domain.MchFollowupPlan;
import com.smartor.domain.MchFollowupPlanItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
 * å¦‡å¹¼éšè®¿æ¶ˆæ¯å‘送器。
 *
 * <p>短信复用 {@link SmsUtils#sendYunMasSms},微信复用
 * {@link SmsUtils#sendChatLs}(即 {@code /sms/sendChatFuyou} çš„内部实现)。
 * ä¸ç»è¿‡æ™®é€šéšè®¿çš„发送方工厂与补偿链路。</p>
 */
@Slf4j
@Component
public class MchFollowupMessageSender {
    @Autowired
    private ISysConfigService configService;
    public MchFollowupSendOutcome sendSms(MchFollowupPlan plan, MchFollowupPlanItem item) {
        String phone = plan == null ? null : plan.getPhone();
        String content = item == null ? null : item.getContent();
        if (StringUtils.isBlank(phone)) {
            return MchFollowupSendOutcome.skip("手机号为空");
        }
        if (StringUtils.isBlank(content)) {
            return MchFollowupSendOutcome.fail("短信内容为空", requestSummary("sms", phone, null), null);
        }
        try {
            String configJson = configService.selectConfigByKey(
                    MchFollowupConstants.CONFIG_YUNMAS, plan.getOrgid());
            SmsUtils.YunMasConfig config = SmsUtils.YunMasConfig.of(configJson);
            SmsUtils.SmsResult result = SmsUtils.sendYunMasSms(config, phone, content);
            String requestBody = requestSummary("sms", phone, null);
            String responseBody = JSON.toJSONString(result);
            if (result != null && result.isOk()) {
                return MchFollowupSendOutcome.ok(result.getMsgGroup(), requestBody, responseBody);
            }
            String message = result == null ? "云MAS返回为空" : result.getMessage();
            return MchFollowupSendOutcome.fail(message, requestBody, responseBody);
        } catch (Exception e) {
            log.error("【妇幼随访】短信发送异常,planId={},itemId={}", plan.getId(), item.getId(), e);
            return MchFollowupSendOutcome.fail("短信发送异常:" + e.getMessage(),
                    requestSummary("sms", phone, null), null);
        }
    }
    public MchFollowupSendOutcome sendWechat(MchFollowupPlan plan, MchFollowupPlanItem item) {
        String phone = plan == null ? null : plan.getPhone();
        if (StringUtils.isBlank(phone) && StringUtils.isBlank(plan == null ? null : plan.getIdcardno())) {
            return MchFollowupSendOutcome.skip("手机号和证件号都为空");
        }
        try {
            String configJson = configService.selectConfigByKey(
                    MchFollowupConstants.CONFIG_LS_WX, plan.getOrgid());
            SmsUtils.LsWxConfig config = SmsUtils.LsWxConfig.of(configJson);
            SmsUtils.LsWxMessage message = new SmsUtils.LsWxMessage();
            message.setId(item.getTemplateId());
            message.setPatientId(plan.getPatid() == null ? null : String.valueOf(plan.getPatid()));
            message.setPatientName(plan.getPatname());
            message.setIdCard(plan.getIdcardno());
            message.setMobile(phone);
            message.setMedCardNo(plan.getSourceBizNo());
            message.setTitleName(item.getTitleName());
            message.setContent(item.getContent());
            message.setUrl(item.getUrl());
            String requestBody = requestSummary("wechat", phone, item.getTemplateId());
            String resp = SmsUtils.sendChatLs(config, message);
            String messageText = parseWechatMessage(resp);
            boolean ok = parseWechatOk(resp);
            if (ok) {
                return MchFollowupSendOutcome.ok(null, requestBody, resp);
            }
            return MchFollowupSendOutcome.fail(messageText, requestBody, resp);
        } catch (Exception e) {
            log.error("【妇幼随访】微信发送异常,planId={},itemId={}", plan.getId(), item.getId(), e);
            return MchFollowupSendOutcome.fail("微信发送异常:" + e.getMessage(),
                    requestSummary("wechat", phone, item == null ? null : item.getTemplateId()), null);
        }
    }
    private boolean parseWechatOk(String resp) {
        if (StringUtils.isBlank(resp)) {
            return false;
        }
        try {
            JSONObject object = JSON.parseObject(resp);
            return object != null && object.getIntValue("code") == 0;
        } catch (Exception e) {
            return false;
        }
    }
    private String parseWechatMessage(String resp) {
        if (StringUtils.isBlank(resp)) {
            return "微信返回为空";
        }
        try {
            JSONObject object = JSON.parseObject(resp);
            if (object == null) {
                return "微信返回为空";
            }
            String msg = object.getString("msg");
            return StringUtils.isBlank(msg) ? resp : msg;
        } catch (Exception e) {
            return resp;
        }
    }
    private String requestSummary(String sendType, String phone, Long templateId) {
        return "sendType=" + sendType
                + ";phone=" + maskPhone(phone)
                + (templateId == null ? "" : ";templateId=" + templateId);
    }
    private String maskPhone(String phone) {
        if (StringUtils.isBlank(phone) || phone.length() < 7) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
    }
}
smartor/src/main/java/com/smartor/service/mch/MchFollowupPeriodParser.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,224 @@
package com.smartor.service.mch;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.smartor.common.MchFollowupConstants;
import com.smartor.domain.MchFollowupNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
/**
 * å¦‡å¹¼éšè®¿å‘¨æœŸ JSON è§£æžå™¨ã€‚
 *
 * <p>支持两种写法:</p>
 * <pre>
 * 1) æ˜¾å¼èŠ‚ç‚¹ï¼š
 * {
 *   "items": [
 *     {"seq":1,"dayOffset":0,"sendTime":"09:00","sendType":"sms","content":"..."},
 *     {"seq":2,"dayOffset":3,"sendType":"wechat","templateId":16,"content":"..."}
 *   ]
 * }
 *
 * 2) é—´éš” + æ¬¡æ•°ï¼š
 * {
 *   "intervalDays": 3,
 *   "count": 4,
 *   "sendType": "sms",
 *   "content": "..."
 * }
 * </pre>
 *
 * <p>dayOffset ä¸€å¾‹è¡¨ç¤ºç›¸å¯¹ plannedFollowTime çš„绝对偏移天数,不是“从上一次发送后顺延”。</p>
 */
@Component
public class MchFollowupPeriodParser {
    public List<MchFollowupNode> parse(String json, String fallbackCycleTimes) {
        if (StringUtils.isBlank(json)) {
            throw new IllegalArgumentException("随访周期 followupPeriod ä¸ºç©º");
        }
        JSONObject root;
        try {
            root = JSON.parseObject(json);
        } catch (Exception e) {
            throw new IllegalArgumentException("随访周期不是合法 JSON:" + e.getMessage(), e);
        }
        if (root == null) {
            throw new IllegalArgumentException("随访周期不是合法 JSON å¯¹è±¡");
        }
        JSONArray items = root.getJSONArray("items");
        if (items != null) {
            return parseItems(items);
        }
        JSONArray days = root.getJSONArray("days");
        if (days != null) {
            return parseDays(days, root);
        }
        Integer intervalDays = root.getInteger("intervalDays");
        if (intervalDays != null) {
            int count = resolveCount(root, fallbackCycleTimes);
            return parseInterval(intervalDays, count, root);
        }
        throw new IllegalArgumentException("随访周期缺少 items / days / intervalDays é…ç½®");
    }
    private List<MchFollowupNode> parseItems(JSONArray items) {
        if (items.isEmpty()) {
            throw new IllegalArgumentException("随访周期 items ä¸èƒ½ä¸ºç©º");
        }
        List<MchFollowupNode> nodes = new ArrayList<>(items.size());
        Set<Integer> seqSet = new HashSet<>();
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = items.getJSONObject(i);
            if (item == null) {
                throw new IllegalArgumentException("随访周期 items[" + i + "] ä¸ºç©º");
            }
            MchFollowupNode node = buildNode(item, i + 1);
            if (!seqSet.add(node.getSeq())) {
                throw new IllegalArgumentException("随访周期 seq é‡å¤ï¼š" + node.getSeq());
            }
            nodes.add(node);
        }
        return nodes;
    }
    private List<MchFollowupNode> parseDays(JSONArray days, JSONObject root) {
        if (days.isEmpty()) {
            throw new IllegalArgumentException("随访周期 days ä¸èƒ½ä¸ºç©º");
        }
        List<MchFollowupNode> nodes = new ArrayList<>(days.size());
        for (int i = 0; i < days.size(); i++) {
            Integer day = days.getInteger(i);
            if (day == null || day < 0) {
                throw new IllegalArgumentException("随访周期 days[" + i + "] å¿…须是非负整数");
            }
            JSONObject item = new JSONObject();
            item.put("seq", i + 1);
            item.put("dayOffset", day);
            copySharedFields(root, item);
            nodes.add(buildNode(item, i + 1));
        }
        return nodes;
    }
    private List<MchFollowupNode> parseInterval(int intervalDays, int count, JSONObject root) {
        if (intervalDays < 0) {
            throw new IllegalArgumentException("intervalDays ä¸èƒ½å°äºŽ 0");
        }
        if (count <= 0) {
            throw new IllegalArgumentException("count å¿…须大于 0");
        }
        List<MchFollowupNode> nodes = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            JSONObject item = new JSONObject();
            item.put("seq", i + 1);
            item.put("dayOffset", intervalDays * i);
            copySharedFields(root, item);
            nodes.add(buildNode(item, i + 1));
        }
        return nodes;
    }
    private MchFollowupNode buildNode(JSONObject item, int defaultSeq) {
        MchFollowupNode node = new MchFollowupNode();
        Integer seq = item.getInteger("seq");
        node.setSeq(seq == null ? defaultSeq : seq);
        if (node.getSeq() <= 0) {
            throw new IllegalArgumentException("随访周期 seq å¿…须大于 0");
        }
        Integer dayOffset = item.getInteger("dayOffset");
        if (dayOffset == null) {
            dayOffset = item.getInteger("day");
        }
        if (dayOffset == null || dayOffset < 0) {
            throw new IllegalArgumentException("随访周期 dayOffset å¿…须是非负整数,seq=" + node.getSeq());
        }
        node.setDayOffset(dayOffset);
        String sendType = normalizeSendType(item.getString("sendType"));
        node.setSendType(sendType);
        node.setSendTime(normalizeSendTime(item.getString("sendTime")));
        node.setContent(item.getString("content"));
        node.setTitleName(item.getString("titleName"));
        node.setTemplateId(item.getLong("templateId"));
        node.setUrl(item.getString("url"));
        if (MchFollowupConstants.SEND_TYPE_SMS.equals(sendType)
                && StringUtils.isBlank(node.getContent())) {
            throw new IllegalArgumentException("短信节点 content ä¸èƒ½ä¸ºç©ºï¼Œseq=" + node.getSeq());
        }
        return node;
    }
    private void copySharedFields(JSONObject root, JSONObject item) {
        copyIfPresent(root, item, "sendTime");
        copyIfPresent(root, item, "sendType");
        copyIfPresent(root, item, "content");
        copyIfPresent(root, item, "titleName");
        copyIfPresent(root, item, "templateId");
        copyIfPresent(root, item, "url");
    }
    private void copyIfPresent(JSONObject from, JSONObject to, String key) {
        if (!to.containsKey(key) && from.containsKey(key)) {
            to.put(key, from.get(key));
        }
    }
    private int resolveCount(JSONObject root, String fallbackCycleTimes) {
        Integer count = root.getInteger("count");
        if (count == null && StringUtils.isNotBlank(fallbackCycleTimes)) {
            try {
                count = Integer.valueOf(fallbackCycleTimes.trim());
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("followupCycleTimes ä¸æ˜¯åˆæ³•次数:" + fallbackCycleTimes);
            }
        }
        if (count == null || count <= 0) {
            throw new IllegalArgumentException("intervalDays æ¨¡å¼å¿…须配置 count æˆ– followupCycleTimes");
        }
        return count;
    }
    static String normalizeSendType(String raw) {
        if (StringUtils.isBlank(raw)) {
            throw new IllegalArgumentException("随访周期 sendType ä¸èƒ½ä¸ºç©º");
        }
        String value = raw.trim().toLowerCase(Locale.ROOT);
        if ("sms".equals(value) || "4".equals(value) || "短信".equals(raw.trim())) {
            return MchFollowupConstants.SEND_TYPE_SMS;
        }
        if ("wechat".equals(value) || "wechat_mp".equals(value) || "5".equals(value)
                || "公众号".equals(raw.trim()) || "微信".equals(raw.trim())) {
            return MchFollowupConstants.SEND_TYPE_WECHAT;
        }
        throw new IllegalArgumentException("不支持的 sendType:" + raw + "(仅支持 sms/wechat)");
    }
    static String normalizeSendTime(String raw) {
        if (StringUtils.isBlank(raw)) {
            return null;
        }
        String value = raw.trim();
        if (value.matches("^([01]\\d|2[0-3]):[0-5]\\d$")) {
            return value;
        }
        if (value.matches("^([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d$")) {
            return value;
        }
        throw new IllegalArgumentException("sendTime æ ¼å¼åº”为 HH:mm æˆ– HH:mm:ss:" + raw);
    }
}
smartor/src/main/java/com/smartor/service/mch/MchFollowupPlanAssembler.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,46 @@
package com.smartor.service.mch;
import com.smartor.common.MchFollowupConstants;
import com.smartor.domain.MchFollowupNode;
import com.smartor.domain.MchFollowupPlanItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * æŠŠè§£æžåŽçš„节点定义组装成可落库的发送节点。
 */
@Component
public class MchFollowupPlanAssembler {
    @Autowired
    private MchFollowupTimeResolver timeResolver;
    public List<MchFollowupPlanItem> assemble(Long planId, Date plannedFollowTime, List<MchFollowupNode> nodes) {
        List<MchFollowupPlanItem> items = new ArrayList<>();
        if (nodes == null || nodes.isEmpty()) {
            return items;
        }
        Date now = new Date();
        for (MchFollowupNode node : nodes) {
            MchFollowupPlanItem item = new MchFollowupPlanItem();
            item.setPlanId(planId);
            item.setSeq(node.getSeq());
            item.setSendType(node.getSendType());
            item.setSendTime(timeResolver.resolve(plannedFollowTime, node));
            item.setTitleName(node.getTitleName());
            item.setContent(node.getContent());
            item.setTemplateId(node.getTemplateId());
            item.setUrl(node.getUrl());
            item.setSendStatus(MchFollowupConstants.ITEM_STATUS_PENDING);
            item.setRetryCount(0);
            item.setCreateTime(now);
            item.setUpdateTime(now);
            items.add(item);
        }
        return items;
    }
}
smartor/src/main/java/com/smartor/service/mch/MchFollowupPlanServiceImpl.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,321 @@
package com.smartor.service.mch;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.smartor.common.MchFollowupConstants;
import com.smartor.common.SpecificArchiveConstants;
import com.smartor.domain.MchFollowupArchiveCandidate;
import com.smartor.domain.MchFollowupNode;
import com.smartor.domain.MchFollowupPlan;
import com.smartor.domain.MchFollowupPlanItem;
import com.smartor.domain.PatChildArchiveDetail;
import com.smartor.domain.PatMaternityArchiveDetail;
import com.smartor.mapper.MchFollowupPlanItemMapper;
import com.smartor.mapper.MchFollowupPlanMapper;
import com.smartor.mapper.PatChildArchiveDetailMapper;
import com.smartor.mapper.PatMaternityArchiveDetailMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
 * å¦‡å¹¼éšè®¿è®¡åˆ’服务实现。
 *
 * <p>只处理丽水市妇幼保健院。计划生成不发送消息,发送由
 * {@link IMchFollowupSendService} ç‹¬ç«‹å®Œæˆã€‚</p>
 */
@Slf4j
@Service
public class MchFollowupPlanServiceImpl implements IMchFollowupPlanService {
    @Autowired
    private MchFollowupPlanMapper planMapper;
    @Autowired
    private MchFollowupPlanItemMapper itemMapper;
    @Autowired
    private PatMaternityArchiveDetailMapper maternityDetailMapper;
    @Autowired
    private PatChildArchiveDetailMapper childDetailMapper;
    @Autowired
    private MchFollowupPeriodParser periodParser;
    @Autowired
    private MchFollowupPlanAssembler planAssembler;
    @Autowired
    private ISysConfigService configService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int rebuildForArchive(String archiveType, Long archiveId, Long archiveDetailId) {
        try {
            return doRebuildForArchive(archiveType, archiveId, archiveDetailId);
        } catch (Exception e) {
            // è®¡åˆ’生成失败不能影响档案主流程,异常在事务边界内消化
            log.error("【妇幼随访】计划重建异常,archiveType={},archiveId={},detailId={}",
                    archiveType, archiveId, archiveDetailId, e);
            return 0;
        }
    }
    private int doRebuildForArchive(String archiveType, Long archiveId, Long archiveDetailId) {
        if (!isEnabled()) {
            return 0;
        }
        ArchiveSnapshot snapshot = loadSnapshot(archiveType, archiveId, archiveDetailId);
        if (snapshot == null) {
            return 0;
        }
        if (snapshot.archiveId == null || snapshot.archiveDetailId == null) {
            log.warn("【妇幼随访】档案主键或详情主键为空,跳过计划重建,archiveType={},archiveId={},detailId={}",
                    archiveType, archiveId, archiveDetailId);
            return 0;
        }
        if (!SpecificArchiveConstants.LISHUI_MCH_ORG_ID.equals(snapshot.orgid)) {
            return 0;
        }
        List<MchFollowupPlan> actives = planMapper.selectActiveByArchive(
                snapshot.archiveType, snapshot.archiveId, snapshot.archiveDetailId);
        if (actives == null) {
            actives = Collections.emptyList();
        }
        for (MchFollowupPlan active : actives) {
            if (sameTime(active.getPlannedFollowTime(), snapshot.plannedFollowTime)
                    && StringUtils.equals(active.getFollowupPeriod(), snapshot.followupPeriod)) {
                MchFollowupPlan contactUpdate = new MchFollowupPlan();
                contactUpdate.setId(active.getId());
                contactUpdate.setCampusid(snapshot.campusid);
                contactUpdate.setSourceBizNo(snapshot.sourceBizNo);
                contactUpdate.setPatname(snapshot.patname);
                contactUpdate.setPhone(snapshot.phone);
                contactUpdate.setIdcardno(snapshot.idcardno);
                contactUpdate.setUpdateTime(DateUtils.getNowDate());
                planMapper.updateMchFollowupPlan(contactUpdate);
                log.debug("【妇幼随访】计划未变化,仅刷新联系人信息,archiveType={},archiveId={},detailId={}",
                        snapshot.archiveType, snapshot.archiveId, snapshot.archiveDetailId);
                return 0;
            }
        }
        Date now = DateUtils.getNowDate();
        for (MchFollowupPlan active : actives) {
            itemMapper.cancelPendingByPlanId(active.getId(), now);
            planMapper.cancelById(active.getId(), now);
        }
        MchFollowupPlan plan = new MchFollowupPlan();
        plan.setOrgid(snapshot.orgid);
        plan.setCampusid(snapshot.campusid);
        plan.setArchiveType(snapshot.archiveType);
        plan.setArchiveId(snapshot.archiveId);
        plan.setArchiveDetailId(snapshot.archiveDetailId);
        plan.setSourceType(snapshot.sourceType);
        plan.setSourceBizNo(snapshot.sourceBizNo);
        plan.setPatid(snapshot.patid);
        plan.setPatname(snapshot.patname);
        plan.setPhone(snapshot.phone);
        plan.setIdcardno(snapshot.idcardno);
        plan.setPlannedFollowTime(snapshot.plannedFollowTime);
        plan.setFollowupPeriod(snapshot.followupPeriod);
        plan.setCreateTime(now);
        plan.setUpdateTime(now);
        if (snapshot.plannedFollowTime == null) {
            plan.setPlanStatus(MchFollowupConstants.PLAN_STATUS_WAITING);
            plan.setRemark("拟随访时间为空,待补充");
            planMapper.insertMchFollowupPlan(plan);
            log.warn("【妇幼随访】拟随访时间为空,生成待补充计划,archiveType={},detailId={}",
                    snapshot.archiveType, snapshot.archiveDetailId);
            return 0;
        }
        List<MchFollowupNode> nodes;
        try {
            nodes = periodParser.parse(snapshot.followupPeriod, snapshot.followupCycleTimes);
        } catch (Exception e) {
            plan.setPlanStatus(MchFollowupConstants.PLAN_STATUS_WAITING);
            plan.setRemark("随访周期JSON解析失败:" + truncate(e.getMessage(), 200));
            planMapper.insertMchFollowupPlan(plan);
            log.error("【妇幼随访】随访周期解析失败,archiveType={},detailId={},period={}",
                    snapshot.archiveType, snapshot.archiveDetailId, snapshot.followupPeriod, e);
            return 0;
        }
        if (nodes.isEmpty()) {
            plan.setPlanStatus(MchFollowupConstants.PLAN_STATUS_WAITING);
            plan.setRemark("随访周期未配置发送节点");
            planMapper.insertMchFollowupPlan(plan);
            return 0;
        }
        plan.setPlanStatus(MchFollowupConstants.PLAN_STATUS_ACTIVE);
        planMapper.insertMchFollowupPlan(plan);
        List<MchFollowupPlanItem> items = planAssembler.assemble(plan.getId(), snapshot.plannedFollowTime, nodes);
        for (MchFollowupPlanItem item : items) {
            itemMapper.insertMchFollowupPlanItem(item);
        }
        log.info("【妇幼随访】计划重建完成,archiveType={},archiveId={},detailId={},节点数={}",
                snapshot.archiveType, snapshot.archiveId, snapshot.archiveDetailId, items.size());
        return items.size();
    }
    @Override
    public int rebuildAll(int limit) {
        if (!isEnabled()) {
            return 0;
        }
        int batch = limit <= 0 ? MchFollowupConstants.DEFAULT_BATCH_SIZE : limit;
        List<MchFollowupArchiveCandidate> candidates =
                planMapper.selectCandidates(SpecificArchiveConstants.LISHUI_MCH_ORG_ID, batch);
        if (candidates == null || candidates.isEmpty()) {
            return 0;
        }
        int generated = 0;
        for (MchFollowupArchiveCandidate candidate : candidates) {
            try {
                generated += rebuildForArchive(candidate.getArchiveType(),
                        candidate.getArchiveId(), candidate.getArchiveDetailId());
            } catch (Exception e) {
                log.error("【妇幼随访】补建计划失败,archiveType={},archiveId={},detailId={}",
                        candidate.getArchiveType(), candidate.getArchiveId(),
                        candidate.getArchiveDetailId(), e);
            }
        }
        return generated;
    }
    private ArchiveSnapshot loadSnapshot(String archiveType, Long archiveId, Long archiveDetailId) {
        if (MchFollowupConstants.ARCHIVE_TYPE_MATERNITY.equals(archiveType)) {
            return loadMaternitySnapshot(archiveId, archiveDetailId);
        }
        if (MchFollowupConstants.ARCHIVE_TYPE_CHILD.equals(archiveType)) {
            return loadChildSnapshot(archiveId, archiveDetailId);
        }
        log.warn("【妇幼随访】未知档案类型:{}", archiveType);
        return null;
    }
    private ArchiveSnapshot loadMaternitySnapshot(Long archiveId, Long archiveDetailId) {
        PatMaternityArchiveDetail detail = null;
        if (archiveDetailId != null) {
            detail = maternityDetailMapper.selectPatMaternityArchiveDetailById(archiveDetailId);
        }
        if (detail == null && archiveId != null) {
            PatMaternityArchiveDetail query = new PatMaternityArchiveDetail();
            query.setArchiveid(archiveId);
            List<PatMaternityArchiveDetail> list =
                    maternityDetailMapper.selectPatMaternityArchiveDetailList(query);
            if (list != null && !list.isEmpty()) {
                detail = list.get(0);
            }
        }
        if (detail == null) {
            return null;
        }
        ArchiveSnapshot snapshot = new ArchiveSnapshot();
        snapshot.archiveType = MchFollowupConstants.ARCHIVE_TYPE_MATERNITY;
        snapshot.archiveId = detail.getArchiveid() == null ? archiveId : detail.getArchiveid();
        snapshot.archiveDetailId = detail.getId();
        snapshot.orgid = detail.getOrgid();
        snapshot.campusid = detail.getCampusid();
        snapshot.sourceType = detail.getSourceType();
        snapshot.sourceBizNo = detail.getSourceBizNo();
        snapshot.patid = detail.getPatid();
        snapshot.patname = detail.getPatname();
        snapshot.phone = detail.getPhone();
        snapshot.idcardno = detail.getIdcardno();
        snapshot.plannedFollowTime = detail.getPlannedFollowTime();
        snapshot.followupPeriod = detail.getFollowupPeriod();
        snapshot.followupCycleTimes = detail.getFollowupCycleTimes();
        return snapshot;
    }
    private ArchiveSnapshot loadChildSnapshot(Long archiveId, Long archiveDetailId) {
        PatChildArchiveDetail detail = null;
        if (archiveDetailId != null) {
            detail = childDetailMapper.selectPatChildArchiveDetailById(archiveDetailId);
        }
        if (detail == null && archiveId != null) {
            PatChildArchiveDetail query = new PatChildArchiveDetail();
            query.setArchiveid(archiveId);
            List<PatChildArchiveDetail> list =
                    childDetailMapper.selectPatChildArchiveDetailList(query);
            if (list != null && !list.isEmpty()) {
                detail = list.get(0);
            }
        }
        if (detail == null) {
            return null;
        }
        ArchiveSnapshot snapshot = new ArchiveSnapshot();
        snapshot.archiveType = MchFollowupConstants.ARCHIVE_TYPE_CHILD;
        snapshot.archiveId = detail.getArchiveid() == null ? archiveId : detail.getArchiveid();
        snapshot.archiveDetailId = detail.getId();
        snapshot.orgid = detail.getOrgid();
        snapshot.campusid = detail.getCampusid();
        snapshot.sourceType = detail.getSourceType();
        snapshot.sourceBizNo = detail.getSourceBizNo();
        snapshot.patid = detail.getPatid();
        snapshot.patname = detail.getPatname();
        snapshot.phone = firstNotBlank(detail.getParentPhone(), detail.getPhone());
        snapshot.idcardno = detail.getIdcardno();
        snapshot.plannedFollowTime = detail.getPlannedFollowTime();
        snapshot.followupPeriod = detail.getFollowupPeriod();
        return snapshot;
    }
    private boolean isEnabled() {
        try {
            String value = configService.selectConfigByKey(MchFollowupConstants.CONFIG_ENABLED);
            return value == null || !"false".equalsIgnoreCase(value.trim());
        } catch (Exception e) {
            log.warn("【妇幼随访】读取启用开关失败,按启用处理:{}", e.getMessage());
            return true;
        }
    }
    private static boolean sameTime(Date left, Date right) {
        if (left == null || right == null) {
            return left == right;
        }
        return Math.abs(left.getTime() - right.getTime()) < 1000L;
    }
    private static String firstNotBlank(String first, String second) {
        return StringUtils.isNotBlank(first) ? first : second;
    }
    private static String truncate(String text, int maxLength) {
        if (text == null || text.length() <= maxLength) {
            return text;
        }
        return text.substring(0, maxLength);
    }
    private static class ArchiveSnapshot {
        private String archiveType;
        private Long archiveId;
        private Long archiveDetailId;
        private String orgid;
        private String campusid;
        private String sourceType;
        private String sourceBizNo;
        private Long patid;
        private String patname;
        private String phone;
        private String idcardno;
        private Date plannedFollowTime;
        private String followupPeriod;
        private String followupCycleTimes;
    }
}
smartor/src/main/java/com/smartor/service/mch/MchFollowupSendOutcome.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,69 @@
package com.smartor.service.mch;
/**
 * å¦‡å¹¼éšè®¿å•次发送结果。
 */
public class MchFollowupSendOutcome {
    private boolean ok;
    private boolean skipped;
    private String message;
    private String providerMsgId;
    private String requestBody;
    private String responseBody;
    public static MchFollowupSendOutcome ok(String providerMsgId, String requestBody, String responseBody) {
        MchFollowupSendOutcome outcome = new MchFollowupSendOutcome();
        outcome.ok = true;
        outcome.providerMsgId = providerMsgId;
        outcome.requestBody = requestBody;
        outcome.responseBody = responseBody;
        return outcome;
    }
    public static MchFollowupSendOutcome fail(String message, String requestBody, String responseBody) {
        MchFollowupSendOutcome outcome = new MchFollowupSendOutcome();
        outcome.ok = false;
        outcome.message = message;
        outcome.requestBody = requestBody;
        outcome.responseBody = responseBody;
        return outcome;
    }
    public static MchFollowupSendOutcome skip(String message) {
        MchFollowupSendOutcome outcome = new MchFollowupSendOutcome();
        outcome.ok = false;
        outcome.skipped = true;
        outcome.message = message;
        return outcome;
    }
    public boolean isOk() {
        return ok;
    }
    public boolean isSkipped() {
        return skipped;
    }
    public String getMessage() {
        return message;
    }
    public String getProviderMsgId() {
        return providerMsgId;
    }
    public String getRequestBody() {
        return requestBody;
    }
    public String getResponseBody() {
        return responseBody;
    }
}
smartor/src/main/java/com/smartor/service/mch/MchFollowupSendServiceImpl.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,210 @@
package com.smartor.service.mch;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.smartor.common.MchFollowupConstants;
import com.smartor.common.SpecificArchiveConstants;
import com.smartor.domain.MchFollowupPlan;
import com.smartor.domain.MchFollowupPlanItem;
import com.smartor.domain.MchFollowupSendLog;
import com.smartor.mapper.MchFollowupPlanItemMapper;
import com.smartor.mapper.MchFollowupPlanMapper;
import com.smartor.mapper.MchFollowupSendLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
 * å¦‡å¹¼éšè®¿å‘送服务实现。
 *
 * <p>只发送丽水妇幼的计划节点;不进入普通随访的补偿发送链路。</p>
 */
@Slf4j
@Service
public class MchFollowupSendServiceImpl implements IMchFollowupSendService {
    @Autowired
    private MchFollowupPlanMapper planMapper;
    @Autowired
    private MchFollowupPlanItemMapper itemMapper;
    @Autowired
    private MchFollowupSendLogMapper sendLogMapper;
    @Autowired
    private MchFollowupMessageSender messageSender;
    @Autowired
    private MchFollowupSendWindow sendWindow;
    @Autowired
    private ISysConfigService configService;
    @Override
    public int sendDue(int limit) {
        if (!isEnabled()) {
            return 0;
        }
        int batch = limit <= 0 ? MchFollowupConstants.DEFAULT_BATCH_SIZE : limit;
        Date now = new Date();
        List<MchFollowupPlanItem> dueItems = itemMapper.selectDueItems(
                SpecificArchiveConstants.LISHUI_MCH_ORG_ID, now, batch);
        if (dueItems == null || dueItems.isEmpty()) {
            return 0;
        }
        int success = 0;
        for (MchFollowupPlanItem item : dueItems) {
            try {
                MchFollowupDueDecision decision = sendWindow.decide(item.getSendTime(), now);
                if (decision == MchFollowupDueDecision.PENDING) {
                    continue;
                }
                if (decision == MchFollowupDueDecision.EXPIRED) {
                    markExpired(item, now);
                    refreshPlanStatus(item.getPlanId());
                    continue;
                }
                if (itemMapper.claimItem(item.getId(), now) != 1) {
                    continue;
                }
                MchFollowupPlan plan = planMapper.selectMchFollowupPlanById(item.getPlanId());
                if (plan == null || !MchFollowupConstants.PLAN_STATUS_ACTIVE.equals(plan.getPlanStatus())) {
                    markCanceled(item, now, "计划不存在或已失效");
                    refreshPlanStatus(item.getPlanId());
                    continue;
                }
                MchFollowupSendOutcome outcome = send(plan, item);
                Date finishTime = new Date();
                if (outcome.isSkipped()) {
                    markSkipped(item, finishTime, outcome.getMessage());
                } else if (outcome.isOk()) {
                    markSuccess(item, finishTime, outcome);
                    success++;
                } else {
                    markFailureOrRetry(item, finishTime, outcome);
                }
                writeLog(item, outcome, now);
                refreshPlanStatus(plan.getId());
            } catch (Exception e) {
                log.error("【妇幼随访】发送节点异常,itemId={},planId={}",
                        item.getId(), item.getPlanId(), e);
                try {
                    markFailureOrRetry(item, new Date(),
                            MchFollowupSendOutcome.fail("发送异常:" + e.getMessage(), null, null));
                    refreshPlanStatus(item.getPlanId());
                } catch (Exception ignore) {
                    log.error("【妇幼随访】异常回写失败,itemId={}", item.getId(), ignore);
                }
            }
        }
        return success;
    }
    private MchFollowupSendOutcome send(MchFollowupPlan plan, MchFollowupPlanItem item) {
        if (MchFollowupConstants.SEND_TYPE_SMS.equals(item.getSendType())) {
            return messageSender.sendSms(plan, item);
        }
        if (MchFollowupConstants.SEND_TYPE_WECHAT.equals(item.getSendType())) {
            return messageSender.sendWechat(plan, item);
        }
        return MchFollowupSendOutcome.fail("不支持的发送方式:" + item.getSendType(), null, null);
    }
    private void markExpired(MchFollowupPlanItem item, Date now) {
        item.setSendStatus(MchFollowupConstants.ITEM_STATUS_EXPIRED);
        item.setNextRetryTime(null);
        item.setSendTimeActual(null);
        item.setProviderMsgId(null);
        item.setResultMsg("超过补发窗口(1天),标记过期");
        item.setUpdateTime(now);
        itemMapper.updateSendResult(item);
        writeLog(item, MchFollowupSendOutcome.fail(item.getResultMsg(), null, null), now);
    }
    private void markCanceled(MchFollowupPlanItem item, Date now, String message) {
        item.setSendStatus(MchFollowupConstants.ITEM_STATUS_CANCELED);
        item.setNextRetryTime(null);
        item.setResultMsg(message);
        item.setUpdateTime(now);
        itemMapper.updateSendResult(item);
    }
    private void markSkipped(MchFollowupPlanItem item, Date now, String message) {
        item.setSendStatus(MchFollowupConstants.ITEM_STATUS_SKIPPED);
        item.setNextRetryTime(null);
        item.setResultMsg(message);
        item.setUpdateTime(now);
        itemMapper.updateSendResult(item);
    }
    private void markSuccess(MchFollowupPlanItem item, Date now, MchFollowupSendOutcome outcome) {
        item.setSendStatus(MchFollowupConstants.ITEM_STATUS_SUCCESS);
        item.setNextRetryTime(null);
        item.setSendTimeActual(now);
        item.setProviderMsgId(outcome.getProviderMsgId());
        item.setResultMsg("发送成功");
        item.setUpdateTime(now);
        itemMapper.updateSendResult(item);
    }
    private void markFailureOrRetry(MchFollowupPlanItem item, Date now, MchFollowupSendOutcome outcome) {
        int retryCount = item.getRetryCount() == null ? 0 : item.getRetryCount();
        retryCount++;
        item.setRetryCount(retryCount);
        item.setSendTimeActual(now);
        item.setProviderMsgId(outcome.getProviderMsgId());
        if (retryCount < MchFollowupConstants.DEFAULT_MAX_RETRY) {
            item.setSendStatus(MchFollowupConstants.ITEM_STATUS_PENDING);
            item.setNextRetryTime(new Date(now.getTime()
                    + MchFollowupConstants.DEFAULT_RETRY_DELAY_MINUTES * 60L * 1000L));
            item.setResultMsg((outcome.getMessage() == null ? "发送失败" : outcome.getMessage())
                    + ",第" + retryCount + "次重试后进入等待");
        } else {
            item.setSendStatus(MchFollowupConstants.ITEM_STATUS_FAILED);
            item.setNextRetryTime(null);
            item.setResultMsg((outcome.getMessage() == null ? "发送失败" : outcome.getMessage())
                    + ",重试次数已达上限");
        }
        item.setUpdateTime(now);
        itemMapper.updateSendResult(item);
    }
    private void writeLog(MchFollowupPlanItem item, MchFollowupSendOutcome outcome, Date now) {
        MchFollowupSendLog sendLog = new MchFollowupSendLog();
        sendLog.setPlanId(item.getPlanId());
        sendLog.setItemId(item.getId());
        sendLog.setSendType(item.getSendType());
        sendLog.setRequestBody(outcome.getRequestBody());
        sendLog.setResponseBody(outcome.getResponseBody());
        sendLog.setSendStatus(item.getSendStatus());
        sendLog.setResultMsg(item.getResultMsg());
        sendLog.setCreateTime(now);
        sendLogMapper.insertMchFollowupSendLog(sendLog);
    }
    private void refreshPlanStatus(Long planId) {
        if (planId == null) {
            return;
        }
        if (itemMapper.countPendingByPlanId(planId) == 0) {
            planMapper.completeById(planId, new Date());
        }
    }
    private boolean isEnabled() {
        try {
            String value = configService.selectConfigByKey(MchFollowupConstants.CONFIG_ENABLED);
            return value == null || !"false".equalsIgnoreCase(value.trim());
        } catch (Exception e) {
            log.warn("【妇幼随访】读取启用开关失败,按启用处理:{}", e.getMessage());
            return true;
        }
    }
}
smartor/src/main/java/com/smartor/service/mch/MchFollowupSendWindow.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,30 @@
package com.smartor.service.mch;
import com.smartor.common.MchFollowupConstants;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
 * å¦‡å¹¼éšè®¿è¡¥å‘窗口判断。
 *
 * <p>只补发 1 å¤©å†…到期的节点;超过 1 å¤©æ ‡è®°è¿‡æœŸï¼Œé¿å…ç»™æ‚£è€…发过时消息。</p>
 */
@Component
public class MchFollowupSendWindow {
    public MchFollowupDueDecision decide(Date sendTime, Date now) {
        if (sendTime == null) {
            return MchFollowupDueDecision.PENDING;
        }
        Date current = now == null ? new Date() : now;
        if (sendTime.after(current)) {
            return MchFollowupDueDecision.PENDING;
        }
        Date expireBefore = new Date(current.getTime() - MchFollowupConstants.CATCHUP_MILLIS);
        if (sendTime.before(expireBefore)) {
            return MchFollowupDueDecision.EXPIRED;
        }
        return MchFollowupDueDecision.SEND;
    }
}
smartor/src/main/java/com/smartor/service/mch/MchFollowupTimeResolver.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,60 @@
package com.smartor.service.mch;
import com.smartor.domain.MchFollowupNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
/**
 * å¦‡å¹¼éšè®¿èŠ‚ç‚¹å‘é€æ—¶é—´è®¡ç®—ã€‚
 *
 * <p>plannedFollowTime æ˜¯æ•´ä¸ªå‘¨æœŸçš„基准日:</p>
 * <pre>
 * send_time = date(plannedFollowTime) + dayOffset + æ—¶åˆ†ç§’
 * </pre>
 *
 * <p>时分秒优先级:item.sendTime &gt; plannedFollowTime çš„æ—¶åˆ†ç§’(非 00:00:00)&gt; 09:00。</p>
 */
@Component
public class MchFollowupTimeResolver {
    private static final LocalTime DEFAULT_TIME = LocalTime.of(9, 0);
    private static final DateTimeFormatter HH_MM = DateTimeFormatter.ofPattern("HH:mm");
    private static final DateTimeFormatter HH_MM_SS = DateTimeFormatter.ofPattern("HH:mm:ss");
    public Date resolve(Date plannedFollowTime, MchFollowupNode node) {
        if (plannedFollowTime == null || node == null || node.getDayOffset() == null) {
            return null;
        }
        LocalDateTime base = LocalDateTime.ofInstant(plannedFollowTime.toInstant(), ZoneId.systemDefault());
        LocalDate sendDate = base.toLocalDate().plusDays(node.getDayOffset());
        LocalTime sendTime = resolveTime(base.toLocalTime(), node.getSendTime());
        return Date.from(LocalDateTime.of(sendDate, sendTime).atZone(ZoneId.systemDefault()).toInstant());
    }
    private LocalTime resolveTime(LocalTime baselineTime, String itemSendTime) {
        if (StringUtils.isNotBlank(itemSendTime)) {
            return parseTime(itemSendTime);
        }
        if (baselineTime != null && baselineTime.toSecondOfDay() != 0) {
            return baselineTime;
        }
        return DEFAULT_TIME;
    }
    private LocalTime parseTime(String value) {
        String text = value.trim();
        if (text.length() == 5) {
            return LocalTime.parse(text, HH_MM);
        }
        return LocalTime.parse(text, HH_MM_SS);
    }
}
smartor/src/main/resources/mapper/smartor/MchFollowupPlanItemMapper.xml
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,128 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.smartor.mapper.MchFollowupPlanItemMapper">
    <resultMap id="MchFollowupPlanItemResult" type="com.smartor.domain.MchFollowupPlanItem">
        <id property="id" column="id"/>
        <result property="planId" column="plan_id"/>
        <result property="seq" column="seq"/>
        <result property="sendType" column="send_type"/>
        <result property="sendTime" column="send_time"/>
        <result property="titleName" column="title_name"/>
        <result property="content" column="content"/>
        <result property="templateId" column="template_id"/>
        <result property="url" column="url"/>
        <result property="sendStatus" column="send_status"/>
        <result property="retryCount" column="retry_count"/>
        <result property="nextRetryTime" column="next_retry_time"/>
        <result property="sendTimeActual" column="send_time_actual"/>
        <result property="resultMsg" column="result_msg"/>
        <result property="providerMsgId" column="provider_msg_id"/>
        <result property="createTime" column="create_time"/>
        <result property="updateTime" column="update_time"/>
    </resultMap>
    <sql id="selectItemVo">
        select id, plan_id, seq, send_type, send_time, title_name, content, template_id, url,
               send_status, retry_count, next_retry_time, send_time_actual,
               result_msg, provider_msg_id, create_time, update_time
        from mch_followup_plan_item
    </sql>
    <insert id="insertMchFollowupPlanItem" parameterType="com.smartor.domain.MchFollowupPlanItem"
            useGeneratedKeys="true" keyProperty="id">
        insert into mch_followup_plan_item
        (plan_id, seq, send_type, send_time, title_name, content, template_id, url,
         send_status, retry_count, next_retry_time, send_time_actual,
         result_msg, provider_msg_id, create_time, update_time)
        values
        (#{planId}, #{seq}, #{sendType}, #{sendTime}, #{titleName}, #{content}, #{templateId}, #{url},
         #{sendStatus}, #{retryCount}, #{nextRetryTime}, #{sendTimeActual},
         #{resultMsg}, #{providerMsgId}, #{createTime}, #{updateTime})
    </insert>
    <update id="updateMchFollowupPlanItem" parameterType="com.smartor.domain.MchFollowupPlanItem">
        update mch_followup_plan_item
        <set>
            <if test="sendType != null">send_type = #{sendType},</if>
            <if test="sendTime != null">send_time = #{sendTime},</if>
            <if test="titleName != null">title_name = #{titleName},</if>
            <if test="content != null">content = #{content},</if>
            <if test="templateId != null">template_id = #{templateId},</if>
            <if test="url != null">url = #{url},</if>
            <if test="sendStatus != null">send_status = #{sendStatus},</if>
            <if test="retryCount != null">retry_count = #{retryCount},</if>
            <if test="nextRetryTime != null">next_retry_time = #{nextRetryTime},</if>
            <if test="sendTimeActual != null">send_time_actual = #{sendTimeActual},</if>
            <if test="resultMsg != null">result_msg = #{resultMsg},</if>
            <if test="providerMsgId != null">provider_msg_id = #{providerMsgId},</if>
            <if test="updateTime != null">update_time = #{updateTime},</if>
        </set>
        where id = #{id}
    </update>
    <update id="updateSendResult" parameterType="com.smartor.domain.MchFollowupPlanItem">
        update mch_followup_plan_item
        set send_status = #{sendStatus,jdbcType=CHAR},
            retry_count = #{retryCount,jdbcType=INTEGER},
            next_retry_time = #{nextRetryTime,jdbcType=TIMESTAMP},
            send_time_actual = #{sendTimeActual,jdbcType=TIMESTAMP},
            result_msg = #{resultMsg,jdbcType=VARCHAR},
            provider_msg_id = #{providerMsgId,jdbcType=VARCHAR},
            update_time = #{updateTime,jdbcType=TIMESTAMP}
        where id = #{id}
    </update>
    <select id="selectMchFollowupPlanItemById" resultMap="MchFollowupPlanItemResult">
        <include refid="selectItemVo"/>
        where id = #{id}
    </select>
    <select id="selectByPlanId" resultMap="MchFollowupPlanItemResult">
        <include refid="selectItemVo"/>
        where plan_id = #{planId}
        order by seq asc, id asc
    </select>
    <select id="selectDueItems" resultMap="MchFollowupPlanItemResult">
        select i.id, i.plan_id, i.seq, i.send_type, i.send_time, i.title_name, i.content,
               i.template_id, i.url, i.send_status, i.retry_count, i.next_retry_time,
               i.send_time_actual, i.result_msg, i.provider_msg_id, i.create_time, i.update_time
        from mch_followup_plan_item i
        inner join mch_followup_plan p on p.id = i.plan_id
        where p.orgid = #{orgid}
          and p.plan_status = '0'
          and i.send_status = '0'
          and i.send_time &lt;= #{now}
          and (i.next_retry_time is null or i.next_retry_time &lt;= #{now})
        order by i.send_time asc, i.seq asc, i.id asc
        limit #{limit}
    </select>
    <update id="claimItem">
        update mch_followup_plan_item
        set send_status = '1',
            update_time = #{now}
        where id = #{id}
          and send_status = '0'
    </update>
    <update id="cancelPendingByPlanId">
        update mch_followup_plan_item
        set send_status = '5',
            result_msg = '计划重建,取消未发送节点',
            update_time = #{now}
        where plan_id = #{planId}
          and send_status = '0'
    </update>
    <select id="countPendingByPlanId" resultType="int">
        select count(1)
        from mch_followup_plan_item
        where plan_id = #{planId}
          and send_status in ('0', '1')
    </select>
</mapper>
smartor/src/main/resources/mapper/smartor/MchFollowupPlanMapper.xml
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,126 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.smartor.mapper.MchFollowupPlanMapper">
    <resultMap id="MchFollowupPlanResult" type="com.smartor.domain.MchFollowupPlan">
        <id property="id" column="id"/>
        <result property="orgid" column="orgid"/>
        <result property="campusid" column="campusid"/>
        <result property="archiveType" column="archive_type"/>
        <result property="archiveId" column="archive_id"/>
        <result property="archiveDetailId" column="archive_detail_id"/>
        <result property="sourceType" column="source_type"/>
        <result property="sourceBizNo" column="source_biz_no"/>
        <result property="patid" column="patid"/>
        <result property="patname" column="patname"/>
        <result property="phone" column="phone"/>
        <result property="idcardno" column="idcardno"/>
        <result property="plannedFollowTime" column="planned_follow_time"/>
        <result property="followupPeriod" column="followup_period"/>
        <result property="planStatus" column="plan_status"/>
        <result property="remark" column="remark"/>
        <result property="createTime" column="create_time"/>
        <result property="updateTime" column="update_time"/>
    </resultMap>
    <sql id="selectPlanVo">
        select id, orgid, campusid, archive_type, archive_id, archive_detail_id,
               source_type, source_biz_no, patid, patname, phone, idcardno,
               planned_follow_time, followup_period, plan_status, remark,
               create_time, update_time
        from mch_followup_plan
    </sql>
    <insert id="insertMchFollowupPlan" parameterType="com.smartor.domain.MchFollowupPlan"
            useGeneratedKeys="true" keyProperty="id">
        insert into mch_followup_plan
        (orgid, campusid, archive_type, archive_id, archive_detail_id,
         source_type, source_biz_no, patid, patname, phone, idcardno,
         planned_follow_time, followup_period, plan_status, remark,
         create_time, update_time)
        values
        (#{orgid}, #{campusid}, #{archiveType}, #{archiveId}, #{archiveDetailId},
         #{sourceType}, #{sourceBizNo}, #{patid}, #{patname}, #{phone}, #{idcardno},
         #{plannedFollowTime}, #{followupPeriod}, #{planStatus}, #{remark},
         #{createTime}, #{updateTime})
    </insert>
    <update id="updateMchFollowupPlan" parameterType="com.smartor.domain.MchFollowupPlan">
        update mch_followup_plan
        <set>
            <if test="orgid != null">orgid = #{orgid},</if>
            <if test="campusid != null">campusid = #{campusid},</if>
            <if test="archiveType != null">archive_type = #{archiveType},</if>
            <if test="archiveId != null">archive_id = #{archiveId},</if>
            <if test="archiveDetailId != null">archive_detail_id = #{archiveDetailId},</if>
            <if test="sourceType != null">source_type = #{sourceType},</if>
            <if test="sourceBizNo != null">source_biz_no = #{sourceBizNo},</if>
            <if test="patid != null">patid = #{patid},</if>
            <if test="patname != null">patname = #{patname},</if>
            <if test="phone != null">phone = #{phone},</if>
            <if test="idcardno != null">idcardno = #{idcardno},</if>
            <if test="plannedFollowTime != null">planned_follow_time = #{plannedFollowTime},</if>
            <if test="followupPeriod != null">followup_period = #{followupPeriod},</if>
            <if test="planStatus != null">plan_status = #{planStatus},</if>
            <if test="remark != null">remark = #{remark},</if>
            <if test="updateTime != null">update_time = #{updateTime},</if>
        </set>
        where id = #{id}
    </update>
    <select id="selectMchFollowupPlanById" resultMap="MchFollowupPlanResult">
        <include refid="selectPlanVo"/>
        where id = #{id}
    </select>
    <select id="selectActiveByArchive" resultMap="MchFollowupPlanResult">
        <include refid="selectPlanVo"/>
        where archive_type = #{archiveType}
          and archive_id = #{archiveId}
        <if test="archiveDetailId != null">
            and archive_detail_id = #{archiveDetailId}
        </if>
          and plan_status in ('0', '3')
        order by id desc
    </select>
    <update id="cancelById">
        update mch_followup_plan
        set plan_status = '1',
            update_time = #{updateTime}
        where id = #{id}
          and plan_status in ('0', '3')
    </update>
    <update id="completeById">
        update mch_followup_plan
        set plan_status = '2',
            update_time = #{updateTime}
        where id = #{id}
          and plan_status = '0'
    </update>
    <select id="selectCandidates" resultType="com.smartor.domain.MchFollowupArchiveCandidate">
        select '1' as archiveType, d.archiveid as archiveId, d.id as archiveDetailId
        from pat_maternity_archive_detail d
        where d.orgid = #{orgid}
          and (d.del_flag is null or d.del_flag = '0')
          and d.planned_follow_time is not null
          and d.followup_period is not null
          and d.followup_period &lt;&gt; ''
          and d.archiveid is not null
        union all
        select '2' as archiveType, d.archiveid as archiveId, d.id as archiveDetailId
        from pat_child_archive_detail d
        where d.orgid = #{orgid}
          and (d.del_flag is null or d.del_flag = '0')
          and d.planned_follow_time is not null
          and d.followup_period is not null
          and d.followup_period &lt;&gt; ''
          and d.archiveid is not null
        limit #{limit}
    </select>
</mapper>
smartor/src/main/resources/mapper/smartor/MchFollowupSendLogMapper.xml
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.smartor.mapper.MchFollowupSendLogMapper">
    <insert id="insertMchFollowupSendLog" parameterType="com.smartor.domain.MchFollowupSendLog"
            useGeneratedKeys="true" keyProperty="id">
        insert into mch_followup_send_log
        (plan_id, item_id, send_type, request_body, response_body, send_status, result_msg, create_time)
        values
        (#{planId}, #{itemId}, #{sendType}, #{requestBody}, #{responseBody}, #{sendStatus}, #{resultMsg}, #{createTime})
    </insert>
</mapper>
smartor/src/test/java/com/smartor/service/mch/MchFollowupLogicCheck.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,183 @@
package com.smartor.service.mch;
import com.smartor.common.MchFollowupConstants;
import com.smartor.domain.MchFollowupNode;
import com.smartor.domain.MchFollowupPlanItem;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
 * å¦‡å¹¼éšè®¿é€»è¾‘自检(纯 main,不依赖 JUnit / Spring / æ•°æ®åº“)。
 *
 * è¦†ç›–:followupPeriod JSON è§£æžã€è®¡åˆ’基准日时间计算、1 å¤©è¡¥å‘窗口、
 * èŠ‚ç‚¹ç»„è£…ã€Mapper XML å¯è§£æžæ€§ã€‚
 */
public final class MchFollowupLogicCheck {
    private static int passed = 0;
    private static int failed = 0;
    private static final SimpleDateFormat DATE_TIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static void check(String key, Object expected, Object actual) {
        boolean ok = expected == null ? actual == null : expected.equals(actual);
        if (ok) {
            passed++;
            System.out.println("  [OK]   " + key + " = " + actual);
        } else {
            failed++;
            System.out.println("  [FAIL] " + key + " æœŸæœ›=" + expected + " å®žé™…=" + actual);
        }
    }
    private static void expectFail(String key, Runnable action) {
        try {
            action.run();
            failed++;
            System.out.println("  [FAIL] " + key + " æœŸæœ›æŠ›å¼‚常,实际未抛");
        } catch (Exception e) {
            passed++;
            System.out.println("  [OK]   " + key + " æŠ›å¼‚常:" + e.getMessage());
        }
    }
    private static Date date(String text) throws Exception {
        return DATE_TIME.parse(text);
    }
    private static MchFollowupPlanAssembler assembler() throws Exception {
        MchFollowupPlanAssembler assembler = new MchFollowupPlanAssembler();
        Field field = MchFollowupPlanAssembler.class.getDeclaredField("timeResolver");
        field.setAccessible(true);
        field.set(assembler, new MchFollowupTimeResolver());
        return assembler;
    }
    private static MchFollowupNode node(int seq, int dayOffset, String sendTime, String sendType) {
        MchFollowupNode node = new MchFollowupNode();
        node.setSeq(seq);
        node.setDayOffset(dayOffset);
        node.setSendTime(sendTime);
        node.setSendType(sendType);
        node.setContent("内容" + seq);
        return node;
    }
    public static void main(String[] args) throws Exception {
        System.out.println("========== å¦‡å¹¼éšè®¿é€»è¾‘自检 ==========");
        MchFollowupPeriodParser parser = new MchFollowupPeriodParser();
        MchFollowupTimeResolver resolver = new MchFollowupTimeResolver();
        MchFollowupSendWindow window = new MchFollowupSendWindow();
        System.out.println("-- 1) items JSON è§£æž --");
        String itemsJson = "{"
                + "\"version\":1,"
                + "\"items\":["
                + "{\"seq\":1,\"dayOffset\":0,\"sendTime\":\"09:00\",\"sendType\":\"sms\",\"content\":\"短信1\"},"
                + "{\"seq\":2,\"dayOffset\":3,\"sendType\":\"5\",\"templateId\":16,\"titleName\":\"提醒\",\"content\":\"微信2\"},"
                + "{\"seq\":3,\"dayOffset\":7,\"sendType\":\"短信\",\"content\":\"短信3\"}"
                + "]}";
        List<MchFollowupNode> itemNodes = parser.parse(itemsJson, null);
        check("节点数", 3, itemNodes.size());
        check("seq1", 1, itemNodes.get(0).getSeq());
        check("dayOffset1", 0, itemNodes.get(0).getDayOffset());
        check("sendType1", "sms", itemNodes.get(0).getSendType());
        check("sendType2", "wechat", itemNodes.get(1).getSendType());
        check("templateId2", 16L, itemNodes.get(1).getTemplateId());
        check("sendTime1", "09:00", itemNodes.get(0).getSendTime());
        System.out.println("-- 2) intervalDays + count è§£æž --");
        String intervalJson = "{\"intervalDays\":3,\"count\":4,\"sendType\":\"sms\",\"content\":\"间隔短信\",\"sendTime\":\"08:30\"}";
        List<MchFollowupNode> intervalNodes = parser.parse(intervalJson, null);
        check("间隔节点数", 4, intervalNodes.size());
        check("节点1偏移", 0, intervalNodes.get(0).getDayOffset());
        check("节点2偏移", 3, intervalNodes.get(1).getDayOffset());
        check("节点3偏移", 6, intervalNodes.get(2).getDayOffset());
        check("节点4偏移", 9, intervalNodes.get(3).getDayOffset());
        check("间隔sendTime", "08:30", intervalNodes.get(0).getSendTime());
        System.out.println("-- 3) intervalDays + followupCycleTimes å…œåº• --");
        List<MchFollowupNode> cycleNodes = parser.parse(
                "{\"intervalDays\":2,\"sendType\":\"wechat\",\"content\":\"微信\"}", "3");
        check("兜底次数", 3, cycleNodes.size());
        check("兜底节点3偏移", 4, cycleNodes.get(2).getDayOffset());
        System.out.println("-- 4) days æ•°ç»„解析 --");
        List<MchFollowupNode> dayNodes = parser.parse(
                "{\"days\":[0,7,14],\"sendType\":\"sms\",\"content\":\"按天\"}", null);
        check("days节点数", 3, dayNodes.size());
        check("days节点2偏移", 7, dayNodes.get(1).getDayOffset());
        System.out.println("-- 5) éžæ³• JSON / éžæ³•字段 --");
        expectFail("非法JSON", () -> parser.parse("{bad", null));
        expectFail("空节点", () -> parser.parse("{\"items\":[]}", null));
        expectFail("非法sendType", () -> parser.parse(
                "{\"items\":[{\"dayOffset\":0,\"sendType\":\"phone\",\"content\":\"x\"}]}", null));
        expectFail("短信缺content", () -> parser.parse(
                "{\"items\":[{\"dayOffset\":0,\"sendType\":\"sms\"}]}", null));
        expectFail("非法sendTime", () -> parser.parse(
                "{\"items\":[{\"dayOffset\":0,\"sendTime\":\"25:00\",\"sendType\":\"sms\",\"content\":\"x\"}]}", null));
        System.out.println("-- 6) åŸºå‡†æ—¥æ—¶é—´è®¡ç®— --");
        Date baseline = date("2026-11-20 14:30:00");
        check("day0沿用14:30", "2026-11-20 14:30:00",
                DATE_TIME.format(resolver.resolve(baseline, node(1, 0, null, "sms"))));
        check("day3沿用14:30", "2026-11-23 14:30:00",
                DATE_TIME.format(resolver.resolve(baseline, node(2, 3, null, "sms"))));
        check("day7显式09:00", "2026-11-27 09:00:00",
                DATE_TIME.format(resolver.resolve(baseline, node(3, 7, "09:00", "wechat"))));
        Date midnight = date("2026-11-20 00:00:00");
        check("基准日00:00默认09:00", "2026-11-20 09:00:00",
                DATE_TIME.format(resolver.resolve(midnight, node(1, 0, null, "sms"))));
        System.out.println("-- 7) 1 å¤©è¡¥å‘窗口 --");
        Date now = date("2026-11-20 12:00:00");
        check("未来节点待发送", MchFollowupDueDecision.PENDING,
                window.decide(date("2026-11-20 12:01:00"), now));
        check("1小时内补发", MchFollowupDueDecision.SEND,
                window.decide(date("2026-11-20 11:00:00"), now));
        check("恰好24小时补发", MchFollowupDueDecision.SEND,
                window.decide(date("2026-11-19 12:00:00"), now));
        check("超过24小时过期", MchFollowupDueDecision.EXPIRED,
                window.decide(date("2026-11-19 11:59:59"), now));
        System.out.println("-- 8) èŠ‚ç‚¹ç»„è£… --");
        List<MchFollowupPlanItem> items = assembler().assemble(99L, baseline, itemNodes);
        check("组装节点数", 3, items.size());
        check("planId", 99L, items.get(0).getPlanId());
        check("初始状态", MchFollowupConstants.ITEM_STATUS_PENDING, items.get(0).getSendStatus());
        check("重试次数", 0, items.get(0).getRetryCount());
        check("组装时间1", "2026-11-20 09:00:00", DATE_TIME.format(items.get(0).getSendTime()));
        check("组装时间3沿用基准日14:30", "2026-11-27 14:30:00", DATE_TIME.format(items.get(2).getSendTime()));
        System.out.println("-- 9) Mapper XML å¯è§£æžæ€§ --");
        String[] xmlFiles = new String[]{
                "smartor/src/main/resources/mapper/smartor/MchFollowupPlanMapper.xml",
                "smartor/src/main/resources/mapper/smartor/MchFollowupPlanItemMapper.xml",
                "smartor/src/main/resources/mapper/smartor/MchFollowupSendLogMapper.xml"
        };
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        for (String xmlFile : xmlFiles) {
            try {
                factory.newDocumentBuilder().parse(new File(xmlFile));
                check(xmlFile, "OK", "OK");
            } catch (Exception e) {
                check(xmlFile, "OK", e.getClass().getSimpleName() + ":" + e.getMessage());
            }
        }
        System.out.println("-- 10) SQL è„šæœ¬å­˜åœ¨æ€§ --");
        check("DDL脚本", true, new File("sql/mch_followup_plan_20261117.sql").isFile());
        System.out.println("========== ç»“果:PASS=" + passed + ",FAIL=" + failed + " ==========");
        if (failed > 0) {
            System.exit(1);
        }
    }
}
smartor/src/test/java/com/smartor/service/mch/MchFollowupPlanServiceCheck.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,283 @@
package com.smartor.service.mch;
import com.ruoyi.system.service.ISysConfigService;
import com.smartor.common.MchFollowupConstants;
import com.smartor.common.SpecificArchiveConstants;
import com.smartor.domain.MchFollowupPlan;
import com.smartor.domain.MchFollowupPlanItem;
import com.smartor.domain.PatChildArchiveDetail;
import com.smartor.domain.PatMaternityArchiveDetail;
import com.smartor.mapper.MchFollowupPlanItemMapper;
import com.smartor.mapper.MchFollowupPlanMapper;
import com.smartor.mapper.PatChildArchiveDetailMapper;
import com.smartor.mapper.PatMaternityArchiveDetailMapper;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * å¦‡å¹¼éšè®¿è®¡åˆ’服务自检(纯 main,使用动态代理模拟 Mapper,不依赖数据库)。
 *
 * è¦†ç›–:计划生成、节点时间、幂等重建、拟随访时间为空、儿保家长电话兜底。
 */
public final class MchFollowupPlanServiceCheck {
    private static int passed = 0;
    private static int failed = 0;
    private static final SimpleDateFormat DATE_TIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static void check(String key, Object expected, Object actual) {
        boolean ok = expected == null ? actual == null : expected.equals(actual);
        if (ok) {
            passed++;
            System.out.println("  [OK]   " + key + " = " + actual);
        } else {
            failed++;
            System.out.println("  [FAIL] " + key + " æœŸæœ›=" + expected + " å®žé™…=" + actual);
        }
    }
    private static Date date(String text) throws Exception {
        return DATE_TIME.parse(text);
    }
    private static void setField(Object target, String name, Object value) throws Exception {
        Field field = target.getClass().getDeclaredField(name);
        field.setAccessible(true);
        field.set(target, value);
    }
    private static Object defaultValue(Class<?> type) {
        if (!type.isPrimitive()) {
            return null;
        }
        if (type == boolean.class) {
            return false;
        }
        if (type == byte.class) {
            return (byte) 0;
        }
        if (type == short.class) {
            return (short) 0;
        }
        if (type == int.class) {
            return 0;
        }
        if (type == long.class) {
            return 0L;
        }
        if (type == float.class) {
            return 0F;
        }
        if (type == double.class) {
            return 0D;
        }
        if (type == char.class) {
            return '\0';
        }
        return null;
    }
    @SuppressWarnings("unchecked")
    private static <T> T proxy(Class<T> type, InvocationHandler handler) {
        return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, handler);
    }
    private static MchFollowupPlanAssembler assembler() throws Exception {
        MchFollowupPlanAssembler assembler = new MchFollowupPlanAssembler();
        setField(assembler, "timeResolver", new MchFollowupTimeResolver());
        return assembler;
    }
    private static PatMaternityArchiveDetail maternityDetail(Long detailId, Long archiveId, Date plannedTime) {
        PatMaternityArchiveDetail detail = new PatMaternityArchiveDetail();
        detail.setId(detailId);
        detail.setArchiveid(archiveId);
        detail.setOrgid(SpecificArchiveConstants.LISHUI_MCH_ORG_ID);
        detail.setCampusid("1");
        detail.setSourceType("1");
        detail.setSourceBizNo("MZ001");
        detail.setPatid(100L);
        detail.setPatname("张三");
        detail.setPhone("13800000000");
        detail.setIdcardno("330102199001010000");
        detail.setPlannedFollowTime(plannedTime);
        detail.setFollowupPeriod("{\"items\":["
                + "{\"dayOffset\":0,\"sendTime\":\"09:00\",\"sendType\":\"sms\",\"content\":\"短信1\"},"
                + "{\"dayOffset\":3,\"sendType\":\"wechat\",\"templateId\":16,\"content\":\"微信2\"},"
                + "{\"dayOffset\":7,\"sendType\":\"sms\",\"content\":\"短信3\"}]}");
        return detail;
    }
    private static PatChildArchiveDetail childDetail(Long detailId, Long archiveId, Date plannedTime) {
        PatChildArchiveDetail detail = new PatChildArchiveDetail();
        detail.setId(detailId);
        detail.setArchiveid(archiveId);
        detail.setOrgid(SpecificArchiveConstants.LISHUI_MCH_ORG_ID);
        detail.setCampusid("1");
        detail.setSourceType("1");
        detail.setSourceBizNo("MZ002");
        detail.setPatid(200L);
        detail.setPatname("李四");
        detail.setPhone("13900000000");
        detail.setParentPhone("13700000000");
        detail.setIdcardno("330102199202020000");
        detail.setPlannedFollowTime(plannedTime);
        detail.setFollowupPeriod("{\"items\":[{\"dayOffset\":1,\"sendType\":\"sms\",\"content\":\"儿保短信\"}]}");
        return detail;
    }
    public static void main(String[] args) throws Exception {
        System.out.println("========== å¦‡å¹¼éšè®¿è®¡åˆ’服务自检 ==========");
        List<MchFollowupPlan> activePlans = new ArrayList<>();
        List<MchFollowupPlanItem> insertedItems = new ArrayList<>();
        long[] planId = {1L};
        long[] itemId = {1L};
        MchFollowupPlanMapper planMapper = proxy(MchFollowupPlanMapper.class, (p, method, a) -> {
            String name = method.getName();
            if ("selectActiveByArchive".equals(name)) {
                return new ArrayList<>(activePlans);
            }
            if ("insertMchFollowupPlan".equals(name)) {
                MchFollowupPlan plan = (MchFollowupPlan) a[0];
                plan.setId(planId[0]++);
                activePlans.add(plan);
                return 1;
            }
            if ("cancelById".equals(name)) {
                Long id = (Long) a[0];
                for (MchFollowupPlan plan : activePlans) {
                    if (id.equals(plan.getId())) {
                        plan.setPlanStatus(MchFollowupConstants.PLAN_STATUS_CANCELED);
                    }
                }
                return 1;
            }
            if ("completeById".equals(name)) {
                return 1;
            }
            return defaultValue(method.getReturnType());
        });
        MchFollowupPlanItemMapper itemMapper = proxy(MchFollowupPlanItemMapper.class, (p, method, a) -> {
            String name = method.getName();
            if ("insertMchFollowupPlanItem".equals(name)) {
                MchFollowupPlanItem item = (MchFollowupPlanItem) a[0];
                item.setId(itemId[0]++);
                insertedItems.add(item);
                return 1;
            }
            if ("cancelPendingByPlanId".equals(name)) {
                return 1;
            }
            if ("countPendingByPlanId".equals(name)) {
                return 1;
            }
            return defaultValue(method.getReturnType());
        });
        Map<Long, PatMaternityArchiveDetail> maternityMap = new HashMap<>();
        maternityMap.put(20L, maternityDetail(20L, 10L, date("2026-11-20 14:30:00")));
        maternityMap.put(21L, maternityDetail(21L, 11L, null));
        PatMaternityArchiveDetailMapper maternityMapper = proxy(PatMaternityArchiveDetailMapper.class, (p, method, a) -> {
            String name = method.getName();
            if ("selectPatMaternityArchiveDetailById".equals(name)) {
                return maternityMap.get((Long) a[0]);
            }
            if ("selectPatMaternityArchiveDetailList".equals(name)) {
                PatMaternityArchiveDetail query = (PatMaternityArchiveDetail) a[0];
                List<PatMaternityArchiveDetail> list = new ArrayList<>();
                for (PatMaternityArchiveDetail detail : maternityMap.values()) {
                    if (query.getArchiveid() == null || query.getArchiveid().equals(detail.getArchiveid())) {
                        list.add(detail);
                    }
                }
                return list;
            }
            return defaultValue(method.getReturnType());
        });
        Map<Long, PatChildArchiveDetail> childMap = new HashMap<>();
        childMap.put(30L, childDetail(30L, 12L, date("2026-12-01 08:00:00")));
        PatChildArchiveDetailMapper childMapper = proxy(PatChildArchiveDetailMapper.class, (p, method, a) -> {
            String name = method.getName();
            if ("selectPatChildArchiveDetailById".equals(name)) {
                return childMap.get((Long) a[0]);
            }
            if ("selectPatChildArchiveDetailList".equals(name)) {
                return new ArrayList<>(childMap.values());
            }
            return defaultValue(method.getReturnType());
        });
        ISysConfigService configService = proxy(ISysConfigService.class, (p, method, a) -> {
            if ("selectConfigByKey".equals(method.getName())) {
                return null;
            }
            return defaultValue(method.getReturnType());
        });
        MchFollowupPlanServiceImpl service = new MchFollowupPlanServiceImpl();
        setField(service, "planMapper", planMapper);
        setField(service, "itemMapper", itemMapper);
        setField(service, "maternityDetailMapper", maternityMapper);
        setField(service, "childDetailMapper", childMapper);
        setField(service, "periodParser", new MchFollowupPeriodParser());
        setField(service, "planAssembler", assembler());
        setField(service, "configService", configService);
        System.out.println("-- 1) å¦‡ä¿è®¡åˆ’生成 --");
        int generated = service.rebuildForArchive(MchFollowupConstants.ARCHIVE_TYPE_MATERNITY, 10L, 20L);
        check("生成节点数", 3, generated);
        check("计划数", 1, activePlans.size());
        check("计划状态", MchFollowupConstants.PLAN_STATUS_ACTIVE, activePlans.get(0).getPlanStatus());
        check("计划机构", SpecificArchiveConstants.LISHUI_MCH_ORG_ID, activePlans.get(0).getOrgid());
        check("节点数", 3, insertedItems.size());
        check("节点1时间", "2026-11-20 09:00:00", DATE_TIME.format(insertedItems.get(0).getSendTime()));
        check("节点2时间", "2026-11-23 14:30:00", DATE_TIME.format(insertedItems.get(1).getSendTime()));
        check("节点3时间", "2026-11-27 14:30:00", DATE_TIME.format(insertedItems.get(2).getSendTime()));
        System.out.println("-- 2) ç›¸åŒåŸºå‡†æ—¥/周期幂等 --");
        int again = service.rebuildForArchive(MchFollowupConstants.ARCHIVE_TYPE_MATERNITY, 10L, 20L);
        check("幂等返回", 0, again);
        check("计划数不变", 1, activePlans.size());
        check("节点数不变", 3, insertedItems.size());
        System.out.println("-- 3) æ‹Ÿéšè®¿æ—¶é—´ä¸ºç©º --");
        int waiting = service.rebuildForArchive(MchFollowupConstants.ARCHIVE_TYPE_MATERNITY, 11L, 21L);
        check("等待计划不生成节点", 0, waiting);
        check("等待计划数", 2, activePlans.size());
        check("等待计划状态", MchFollowupConstants.PLAN_STATUS_WAITING, activePlans.get(1).getPlanStatus());
        System.out.println("-- 4) å„¿ä¿å®¶é•¿ç”µè¯å…œåº• --");
        int childGenerated = service.rebuildForArchive(MchFollowupConstants.ARCHIVE_TYPE_CHILD, 12L, 30L);
        check("儿保节点数", 1, childGenerated);
        check("儿保计划数", 3, activePlans.size());
        check("儿保电话", "13700000000", activePlans.get(2).getPhone());
        check("儿保节点时间", "2026-12-02 08:00:00",
                DATE_TIME.format(insertedItems.get(insertedItems.size() - 1).getSendTime()));
        System.out.println("-- 5) éžä¸½æ°´å¦‡å¹¼ä¸ç”Ÿæˆ --");
        PatMaternityArchiveDetail other = maternityDetail(40L, 20L, date("2026-11-20 14:30:00"));
        other.setOrgid("OTHER_ORG");
        maternityMap.put(40L, other);
        int otherGenerated = service.rebuildForArchive(MchFollowupConstants.ARCHIVE_TYPE_MATERNITY, 20L, 40L);
        check("其他机构不生成", 0, otherGenerated);
        System.out.println("========== ç»“果:PASS=" + passed + ",FAIL=" + failed + " ==========");
        if (failed > 0) {
            System.exit(1);
        }
    }
}
smartor/src/test/java/com/smartor/service/mch/MchFollowupSendServiceCheck.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,198 @@
package com.smartor.service.mch;
import com.ruoyi.system.service.ISysConfigService;
import com.smartor.common.MchFollowupConstants;
import com.smartor.domain.MchFollowupPlan;
import com.smartor.domain.MchFollowupPlanItem;
import com.smartor.domain.MchFollowupSendLog;
import com.smartor.mapper.MchFollowupPlanItemMapper;
import com.smartor.mapper.MchFollowupPlanMapper;
import com.smartor.mapper.MchFollowupSendLogMapper;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * å¦‡å¹¼éšè®¿å‘送服务自检(纯 main,动态代理模拟 Mapper,不依赖数据库/第三方接口)。
 */
public final class MchFollowupSendServiceCheck {
    private static int passed = 0;
    private static int failed = 0;
    private static void check(String key, Object expected, Object actual) {
        boolean ok = expected == null ? actual == null : expected.equals(actual);
        if (ok) {
            passed++;
            System.out.println("  [OK]   " + key + " = " + actual);
        } else {
            failed++;
            System.out.println("  [FAIL] " + key + " æœŸæœ›=" + expected + " å®žé™…=" + actual);
        }
    }
    private static void setField(Object target, String name, Object value) throws Exception {
        Field field = target.getClass().getDeclaredField(name);
        field.setAccessible(true);
        field.set(target, value);
    }
    private static Object defaultValue(Class<?> type) {
        if (!type.isPrimitive()) {
            return null;
        }
        if (type == boolean.class) {
            return false;
        }
        if (type == int.class) {
            return 0;
        }
        if (type == long.class) {
            return 0L;
        }
        return null;
    }
    @SuppressWarnings("unchecked")
    private static <T> T proxy(Class<T> type, InvocationHandler handler) {
        return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, handler);
    }
    private static MchFollowupPlanItem item(String sendType, long sendTimeMillis) {
        MchFollowupPlanItem item = new MchFollowupPlanItem();
        item.setId(1L);
        item.setPlanId(10L);
        item.setSeq(1);
        item.setSendType(sendType);
        item.setSendTime(new Date(sendTimeMillis));
        item.setContent("内容");
        item.setSendStatus(MchFollowupConstants.ITEM_STATUS_PENDING);
        item.setRetryCount(0);
        return item;
    }
    private static MchFollowupPlan plan() {
        MchFollowupPlan plan = new MchFollowupPlan();
        plan.setId(10L);
        plan.setOrgid("47226079133110211G1001");
        plan.setPlanStatus(MchFollowupConstants.PLAN_STATUS_ACTIVE);
        plan.setPhone("13800000000");
        return plan;
    }
    private static int run(MchFollowupPlanItem targetItem, MchFollowupMessageSender sender,
                           boolean expectClaim) throws Exception {
        List<MchFollowupPlanItem> dueItems = new ArrayList<>();
        dueItems.add(targetItem);
        List<MchFollowupSendLog> logs = new ArrayList<>();
        boolean[] claimed = {false};
        boolean[] planCompleted = {false};
        MchFollowupPlanItemMapper itemMapper = proxy(MchFollowupPlanItemMapper.class, (p, method, a) -> {
            String name = method.getName();
            if ("selectDueItems".equals(name)) {
                return dueItems;
            }
            if ("claimItem".equals(name)) {
                claimed[0] = true;
                return 1;
            }
            if ("updateSendResult".equals(name)) {
                return 1;
            }
            if ("countPendingByPlanId".equals(name)) {
                return 0;
            }
            return defaultValue(method.getReturnType());
        });
        MchFollowupPlanMapper planMapper = proxy(MchFollowupPlanMapper.class, (p, method, a) -> {
            String name = method.getName();
            if ("selectMchFollowupPlanById".equals(name)) {
                return plan();
            }
            if ("completeById".equals(name)) {
                planCompleted[0] = true;
                return 1;
            }
            return defaultValue(method.getReturnType());
        });
        MchFollowupSendLogMapper logMapper = proxy(MchFollowupSendLogMapper.class, (p, method, a) -> {
            if ("insertMchFollowupSendLog".equals(method.getName())) {
                logs.add((MchFollowupSendLog) a[0]);
                return 1;
            }
            return defaultValue(method.getReturnType());
        });
        ISysConfigService configService = proxy(ISysConfigService.class, (p, method, a) -> {
            if ("selectConfigByKey".equals(method.getName())) {
                return null;
            }
            return defaultValue(method.getReturnType());
        });
        MchFollowupSendServiceImpl service = new MchFollowupSendServiceImpl();
        setField(service, "planMapper", planMapper);
        setField(service, "itemMapper", itemMapper);
        setField(service, "sendLogMapper", logMapper);
        setField(service, "messageSender", sender);
        setField(service, "sendWindow", new MchFollowupSendWindow());
        setField(service, "configService", configService);
        int sent = service.sendDue(10);
        check("claimItem调用", expectClaim, claimed[0]);
        check("计划完成更新", true, planCompleted[0]);
        check("发送日志数", 1, logs.size());
        return sent;
    }
    public static void main(String[] args) throws Exception {
        System.out.println("========== å¦‡å¹¼éšè®¿å‘送服务自检 ==========");
        long now = System.currentTimeMillis();
        System.out.println("-- 1) çŸ­ä¿¡å‘送成功 --");
        MchFollowupPlanItem smsItem = item(MchFollowupConstants.SEND_TYPE_SMS, now - 60L * 60L * 1000L);
        MchFollowupMessageSender okSender = new MchFollowupMessageSender() {
            @Override
            public MchFollowupSendOutcome sendSms(MchFollowupPlan plan, MchFollowupPlanItem item) {
                return MchFollowupSendOutcome.ok("MSG-1", "req", "resp");
            }
            @Override
            public MchFollowupSendOutcome sendWechat(MchFollowupPlan plan, MchFollowupPlanItem item) {
                return MchFollowupSendOutcome.fail("微信失败", "req", "resp");
            }
        };
        int success = run(smsItem, okSender, true);
        check("成功数量", 1, success);
        check("节点状态", MchFollowupConstants.ITEM_STATUS_SUCCESS, smsItem.getSendStatus());
        check("第三方ID", "MSG-1", smsItem.getProviderMsgId());
        System.out.println("-- 2) è¶…过 1 å¤©æ ‡è®°è¿‡æœŸ --");
        MchFollowupPlanItem expiredItem = item(
                MchFollowupConstants.SEND_TYPE_SMS, now - 25L * 60L * 60L * 1000L);
        int expiredSent = run(expiredItem, okSender, false);
        check("过期不发送", 0, expiredSent);
        check("过期状态", MchFollowupConstants.ITEM_STATUS_EXPIRED, expiredItem.getSendStatus());
        System.out.println("-- 3) å¾®ä¿¡å¤±è´¥è¿›å…¥é‡è¯• --");
        MchFollowupPlanItem retryItem = item(
                MchFollowupConstants.SEND_TYPE_WECHAT, now - 60L * 60L * 1000L);
        int retrySent = run(retryItem, okSender, true);
        check("失败不计数", 0, retrySent);
        check("重试状态", MchFollowupConstants.ITEM_STATUS_PENDING, retryItem.getSendStatus());
        check("重试次数", 1, retryItem.getRetryCount());
        check("下次重试时间非空", true, retryItem.getNextRetryTime() != null);
        System.out.println("========== ç»“果:PASS=" + passed + ",FAIL=" + failed + " ==========");
        if (failed > 0) {
            System.exit(1);
        }
    }
}
sql/mch_followup_plan_20261117.sql
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,81 @@
-- =============================================================================
-- å¦‡å¹¼éšè®¿æŒ‰å‘¨æœŸå‘送:计划表 + èŠ‚ç‚¹è¡¨ + å‘送日志表
-- é€‚用机构:丽水市妇幼保健院 orgid = 47226079133110211G1001
-- æ—¥æœŸï¼š2026-11-17
-- =============================================================================
-- 1. followup_period æ”¹ä¸º TEXT,容纳 JSON(原 varchar(100) æ”¾ä¸ä¸‹å‘送内容)
ALTER TABLE pat_maternity_archive_detail
    MODIFY COLUMN followup_period TEXT NULL COMMENT '随访周期JSON';
ALTER TABLE pat_child_archive_detail
    MODIFY COLUMN followup_period TEXT NULL COMMENT '随访周期JSON';
ALTER TABLE pat_specific_archive_generate_config
    MODIFY COLUMN followup_period TEXT NULL COMMENT '随访周期JSON';
-- 2. å¦‡å¹¼éšè®¿è®¡åˆ’主表
CREATE TABLE IF NOT EXISTS mch_followup_plan (
    id                  BIGINT       NOT NULL AUTO_INCREMENT COMMENT '主键',
    orgid               VARCHAR(64)  NOT NULL COMMENT '机构ID',
    campusid            VARCHAR(64)  DEFAULT NULL COMMENT '院区ID',
    archive_type        VARCHAR(8)   NOT NULL COMMENT '档案类型:1妇保 2儿保',
    archive_id          BIGINT       NOT NULL COMMENT '档案主表ID',
    archive_detail_id   BIGINT       NOT NULL COMMENT '档案详情ID',
    source_type         VARCHAR(8)   DEFAULT NULL COMMENT '来源类型:1门诊 2住院随访 3手工',
    source_biz_no       VARCHAR(128) DEFAULT NULL COMMENT '来源业务编号:门诊号/住院号',
    patid               BIGINT       DEFAULT NULL COMMENT '患者ID',
    patname             VARCHAR(255) DEFAULT NULL COMMENT '患者姓名',
    phone               VARCHAR(32)  DEFAULT NULL COMMENT '联系电话',
    idcardno            VARCHAR(64)  DEFAULT NULL COMMENT '证件号码',
    planned_follow_time DATETIME     DEFAULT NULL COMMENT '周期基准日',
    followup_period     TEXT         DEFAULT NULL COMMENT '随访周期JSON快照',
    plan_status         CHAR(1)      NOT NULL DEFAULT '0' COMMENT '状态:0有效 1取消 2完成 3待补充/配置异常',
    remark              VARCHAR(500) DEFAULT NULL COMMENT '备注',
    create_time         DATETIME     DEFAULT NULL,
    update_time         DATETIME     DEFAULT NULL,
    PRIMARY KEY (id),
    KEY idx_mch_plan_archive (archive_type, archive_id, archive_detail_id),
    KEY idx_mch_plan_status (orgid, plan_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='妇幼随访计划主表';
-- 3. å¦‡å¹¼éšè®¿è®¡åˆ’发送节点
CREATE TABLE IF NOT EXISTS mch_followup_plan_item (
    id                BIGINT       NOT NULL AUTO_INCREMENT COMMENT '主键',
    plan_id           BIGINT       NOT NULL COMMENT '计划ID',
    seq               INT          NOT NULL COMMENT '节点顺序',
    send_type         VARCHAR(16)  NOT NULL COMMENT '发送方式:sms/wechat',
    send_time         DATETIME     NOT NULL COMMENT '发送时间',
    title_name        VARCHAR(255) DEFAULT NULL COMMENT '微信标题',
    content           TEXT         DEFAULT NULL COMMENT '发送内容',
    template_id       BIGINT       DEFAULT NULL COMMENT '微信模板ID',
    url               VARCHAR(1000) DEFAULT NULL COMMENT '微信跳转地址',
    send_status       CHAR(1)      NOT NULL DEFAULT '0' COMMENT '状态:0待发送 1发送中 2成功 3失败 4过期 5取消 6跳过',
    retry_count       INT          NOT NULL DEFAULT 0 COMMENT '已重试次数',
    next_retry_time   DATETIME     DEFAULT NULL COMMENT '下次重试时间',
    send_time_actual  DATETIME     DEFAULT NULL COMMENT '实际发送时间',
    result_msg        VARCHAR(1000) DEFAULT NULL COMMENT '结果说明',
    provider_msg_id   VARCHAR(255) DEFAULT NULL COMMENT '第三方消息ID',
    create_time       DATETIME     DEFAULT NULL,
    update_time       DATETIME     DEFAULT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uk_mch_plan_seq (plan_id, seq),
    KEY idx_mch_item_due (send_status, send_time),
    KEY idx_mch_item_plan (plan_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='妇幼随访计划发送节点';
-- 4. å¦‡å¹¼éšè®¿å‘送日志
CREATE TABLE IF NOT EXISTS mch_followup_send_log (
    id            BIGINT       NOT NULL AUTO_INCREMENT COMMENT '主键',
    plan_id       BIGINT       DEFAULT NULL COMMENT '计划ID',
    item_id       BIGINT       DEFAULT NULL COMMENT '节点ID',
    send_type     VARCHAR(16)  DEFAULT NULL COMMENT '发送方式',
    request_body  TEXT         DEFAULT NULL COMMENT '请求摘要(手机号脱敏)',
    response_body TEXT         DEFAULT NULL COMMENT '第三方响应',
    send_status   CHAR(1)      DEFAULT NULL COMMENT '发送后状态',
    result_msg    VARCHAR(1000) DEFAULT NULL COMMENT '结果说明',
    create_time   DATETIME     DEFAULT NULL,
    PRIMARY KEY (id),
    KEY idx_mch_log_item (item_id),
    KEY idx_mch_log_plan (plan_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='妇幼随访发送日志';