陈昶聿
3 天以前 3acf9415fce2dd21c0fd5d67805b72a8bde24a81
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
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;
        }
    }
}