自动化立体仓库 - WMS系统
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package com.zy.asrs.task.handler;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.core.common.Cools;
import com.zy.asrs.entity.WrkDetl;
import com.zy.asrs.entity.WrkMast;
import com.zy.asrs.entity.param.ErpOutTaskLockReportParam;
import com.zy.asrs.service.ApiLogService;
import com.zy.asrs.service.WrkDetlService;
import com.zy.asrs.service.WrkMastService;
import com.zy.asrs.task.AbstractHandler;
import com.zy.asrs.task.core.ReturnT;
import com.zy.common.entity.Parameter;
import com.zy.common.utils.HttpHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
 
@Slf4j
@Service
public class WorkOutLockErpReportHandler extends AbstractHandler<String> {
 
    public static final long ERP_LOCK_REPORT_PENDING_WRK_STS = 13L;
    public static final long ERP_LOCK_REPORT_SUCCESS_WRK_STS = 21L;
    public static final long ERP_LOCK_REPORT_FAIL_WRK_STS = 22L;
    public static final int ERP_LOCK_REPORT_MAX_RETRY_TIMES = 3;
    public static final String ERP_LOCK_REPORT_PENDING_FLAG = "P";
    public static final String ERP_LOCK_REPORT_SUCCESS_FLAG = "Y";
    public static final String ERP_LOCK_REPORT_FAIL_FLAG = "F";
 
    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
 
    @Autowired
    private WrkMastService wrkMastService;
    @Autowired
    private WrkDetlService wrkDetlService;
    @Autowired
    private ApiLogService apiLogService;
 
    @Value("${erp.switch.ErpReportOld}")
    private boolean erpReportOld;
 
    @Value("${erp.address.URL:}")
    private String erpUrl;
 
    @Value("${erp.address.OutLockaddress:}")
    private String erpOutLockAddress;
 
    /**
     * 7.12 出库任务锁定。
     * WCS 出库任务开始后,WMS 向 ERP 上报 palletId、orderId;失败最多重试三次。
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnT<String> start(WrkMast source) {
        WrkMast wrkMast = wrkMastService.selectById(source.getWrkNo());
        if (wrkMast == null || !Long.valueOf(ERP_LOCK_REPORT_PENDING_WRK_STS).equals(wrkMast.getWrkSts())) {
            return SUCCESS;
        }
 
        if (!isErpReportEnabled()) {
            finishReport(wrkMast, false, getRetryTimes(wrkMast), "ERP reporting is disabled", false);
            return FAIL.setMsg("ERP reporting is disabled");
        }
        if (Cools.isEmpty(erpOutLockAddress)) {
            return failWithoutCallingErp(wrkMast, "ERP出库任务锁定上报地址未配置");
        }
 
        List<WrkDetl> wrkDetls = wrkDetlService.selectByWrkNo(wrkMast.getWrkNo());
        ErpOutTaskLockReportParam param = buildParam(wrkMast, wrkDetls);
        String validateMsg = validateParam(param);
        if (!Cools.isEmpty(validateMsg)) {
            return failWithoutCallingErp(wrkMast, validateMsg);
        }
 
        String request = JSON.toJSONString(param);
        String response = "";
        boolean success = false;
        String errorMsg = null;
        String requestUrl = buildRequestUrl();
 
        try {
            response = new HttpHandler.Builder()
                    .setUri(erpUrl)
                    .setPath(erpOutLockAddress)
                    .setJson(request)
                    .build()
                    .doPost();
            success = isErpReportSuccess(response);
            if (!success) {
                errorMsg = extractErrorMsg(response);
            }
            finishReport(wrkMast, success, getRetryTimes(wrkMast), errorMsg, true);
        } catch (Exception e) {
            errorMsg = e.getMessage();
            finishReport(wrkMast, false, getRetryTimes(wrkMast), errorMsg, true);
        } finally {
            try {
                apiLogService.save(
                        "Outbound ERP Lock Report",
                        requestUrl,
                        null,
                        "127.0.0.1",
                        request,
                        response,
                        success,
                        "workNo=" + wrkMast.getWrkNo()
                );
            } catch (Exception logEx) {
                log.error("save outbound erp lock api log failed", logEx);
            }
        }
 
        if (success) {
            return SUCCESS;
        }
        return FAIL.setMsg(errorMsg);
    }
 
    private ReturnT<String> failWithoutCallingErp(WrkMast wrkMast, String errorMsg) {
        finishReport(wrkMast, false, getRetryTimes(wrkMast), errorMsg, true);
        return FAIL.setMsg(errorMsg);
    }
 
    private boolean isErpReportEnabled() {
        if (!erpReportOld) {
            return false;
        }
        String erpReport = Parameter.get().getErpReport();
        return Cools.isEmpty(erpReport) || "true".equalsIgnoreCase(erpReport);
    }
 
    private ErpOutTaskLockReportParam buildParam(WrkMast wrkMast, List<WrkDetl> wrkDetls) {
        ErpOutTaskLockReportParam param = new ErpOutTaskLockReportParam();
        param.setPalletId(resolvePalletId(wrkMast, wrkDetls));
        param.setOrderId(resolveOrderId(wrkMast, wrkDetls));
        param.setStartTime(formatDate(new Date()));
        return param;
    }
 
    private String formatDate(Date date) {
        if (date == null) {
            return null;
        }
        return new SimpleDateFormat(DATE_TIME_PATTERN).format(date);
    }
 
    private String resolvePalletId(WrkMast wrkMast, List<WrkDetl> wrkDetls) {
        if (!Cools.isEmpty(wrkMast.getBarcode())) {
            return wrkMast.getBarcode();
        }
        if (wrkDetls == null) {
            return null;
        }
        for (WrkDetl wrkDetl : wrkDetls) {
            if (!Cools.isEmpty(wrkDetl.getZpallet())) {
                return wrkDetl.getZpallet();
            }
        }
        return null;
    }
 
    private String resolveOrderId(WrkMast wrkMast, List<WrkDetl> wrkDetls) {
        if (wrkDetls != null) {
            for (WrkDetl wrkDetl : wrkDetls) {
                if (!Cools.isEmpty(wrkDetl.getOrderNo())) {
                    return wrkDetl.getOrderNo();
                }
            }
        }
        return wrkMast.getUserNo();
    }
 
    private String validateParam(ErpOutTaskLockReportParam param) {
        if (param == null || Cools.isEmpty(param.getPalletId())) {
            return "ERP出库任务锁定上报失败:palletId为空";
        }
        if (Cools.isEmpty(param.getOrderId())) {
            return "ERP出库任务锁定上报失败:orderId为空";
        }
        return null;
    }
 
    private boolean isErpReportSuccess(String response) {
        if (Cools.isEmpty(response)) {
            return false;
        }
        try {
            JSONObject jsonObject = JSON.parseObject(response);
            if (jsonObject == null) {
                return false;
            }
            Boolean success = jsonObject.getBoolean("success");
            if (success != null) {
                return success;
            }
            Integer code = jsonObject.getInteger("code");
            if (code != null) {
                return code == 200 || code == 0;
            }
            Integer status = jsonObject.getInteger("status");
            if (status != null) {
                return status == 200 || status == 0;
            }
            String result = jsonObject.getString("result");
            if (!Cools.isEmpty(result)) {
                return "success".equalsIgnoreCase(result) || "ok".equalsIgnoreCase(result) || "true".equalsIgnoreCase(result);
            }
        } catch (Exception ignore) {
            return response.toLowerCase().contains("success") && response.toLowerCase().contains("true");
        }
        return false;
    }
 
    private String extractErrorMsg(String response) {
        if (Cools.isEmpty(response)) {
            return "empty erp response";
        }
        try {
            JSONObject jsonObject = JSON.parseObject(response);
            if (jsonObject == null) {
                return response;
            }
            String[] keys = new String[]{"msg", "message", "error", "errMsg"};
            for (String key : keys) {
                String value = jsonObject.getString(key);
                if (!Cools.isEmpty(value)) {
                    return value;
                }
            }
        } catch (Exception ignore) {
        }
        return response;
    }
 
    private int getRetryTimes(WrkMast wrkMast) {
        if (wrkMast.getExpTime() == null) {
            return 0;
        }
        return wrkMast.getExpTime().intValue();
    }
 
    private void finishReport(WrkMast wrkMast, boolean success, int currentRetryTimes, String errorMsg, boolean countCurrentAttempt) {
        int retryTimes = currentRetryTimes + (countCurrentAttempt ? 1 : 0);
        Date now = new Date();
        wrkMast.setExpTime((double) retryTimes);
        wrkMast.setModiTime(now);
        if (success) {
            wrkMast.setWrkSts(ERP_LOCK_REPORT_SUCCESS_WRK_STS);
            wrkMast.setLogMk(ERP_LOCK_REPORT_SUCCESS_FLAG);
            wrkMast.setLogErrMemo(null);
            wrkMast.setLogErrTime(null);
        } else {
            wrkMast.setLogErrMemo(truncate(errorMsg, 500));
            wrkMast.setLogErrTime(now);
            if (retryTimes >= ERP_LOCK_REPORT_MAX_RETRY_TIMES || !countCurrentAttempt) {
                wrkMast.setWrkSts(ERP_LOCK_REPORT_FAIL_WRK_STS);
                wrkMast.setLogMk(ERP_LOCK_REPORT_FAIL_FLAG);
            } else {
                wrkMast.setWrkSts(ERP_LOCK_REPORT_PENDING_WRK_STS);
                wrkMast.setLogMk(ERP_LOCK_REPORT_PENDING_FLAG);
            }
        }
        if (!wrkMastService.updateById(wrkMast)) {
            throw new IllegalStateException("update outbound erp lock report status failed, workNo=" + wrkMast.getWrkNo());
        }
    }
 
    private String truncate(String message, int maxLength) {
        if (message == null || message.length() <= maxLength) {
            return message;
        }
        return message.substring(0, maxLength);
    }
 
    private String buildRequestUrl() {
        if (Cools.isEmpty(erpUrl)) {
            return erpOutLockAddress;
        }
        if (erpOutLockAddress == null) {
            return erpUrl;
        }
        if (erpUrl.endsWith("/") && erpOutLockAddress.startsWith("/")) {
            return erpUrl + erpOutLockAddress.substring(1);
        }
        if (!erpUrl.endsWith("/") && !erpOutLockAddress.startsWith("/")) {
            return erpUrl + "/" + erpOutLockAddress;
        }
        return erpUrl + erpOutLockAddress;
    }
}