自动化立体仓库 - WMS系统
#
zwl
12 小时以前 60f504b1f7308bcf8d1079a25d0db6922926ebae
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
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.ErpPakoutReportParam;
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 WorkOutErpReportHandler extends AbstractHandler<String> {
 
    public static final long ERP_REPORT_PENDING_WRK_STS = 17L;
    public static final long ERP_REPORT_FINISHED_WRK_STS = 15L;
    public static final int ERP_REPORT_MAX_RETRY_TIMES = 3;
    public static final String ERP_REPORT_PENDING_FLAG = "P";
    public static final String ERP_REPORT_SUCCESS_FLAG = "Y";
    public static final String ERP_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.Outaddress}")
    private String erpOutAddress;
 
    @Transactional(rollbackFor = Exception.class)
    public ReturnT<String> start(WrkMast source) {
        WrkMast wrkMast = wrkMastService.selectById(source.getWrkNo());
        if (wrkMast == null || !Long.valueOf(ERP_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");
        }
 
        ErpPakoutReportParam param = buildParam(wrkMast);
        String request = JSON.toJSONString(param);
        String response = "";
        boolean success = false;
        String errorMsg = null;
        String requestUrl = buildRequestUrl();
 
        try {
            response = new HttpHandler.Builder()
                    .setUri(erpUrl)
                    .setPath(erpOutAddress)
                    .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 Report",
                        requestUrl,
                        null,
                        "127.0.0.1",
                        request,
                        response,
                        success,
                        "workNo=" + wrkMast.getWrkNo()
                );
            } catch (Exception logEx) {
                log.error("save outbound erp api log failed", logEx);
            }
        }
 
        if (success) {
            return SUCCESS;
        }
        return FAIL.setMsg(errorMsg);
    }
 
    private boolean isErpReportEnabled() {
        if (!erpReportOld) {
            return false;
        }
        String erpReport = Parameter.get().getErpReport();
        return Cools.isEmpty(erpReport) || "true".equalsIgnoreCase(erpReport);
    }
 
    private ErpPakoutReportParam buildParam(WrkMast wrkMast) {
        ErpPakoutReportParam param = new ErpPakoutReportParam();
        param.setPalletId(resolvePalletId(wrkMast));
        param.setCreateTime(formatDate(resolveCreateTime(wrkMast)));
        param.setStartTime(formatDate(resolveStartTime(wrkMast)));
        return param;
    }
 
    private String resolvePalletId(WrkMast wrkMast) {
        if (!Cools.isEmpty(wrkMast.getBarcode())) {
            return wrkMast.getBarcode();
        }
        List<WrkDetl> wrkDetls = wrkDetlService.selectByWrkNo(wrkMast.getWrkNo());
        for (WrkDetl wrkDetl : wrkDetls) {
            if (!Cools.isEmpty(wrkDetl.getZpallet())) {
                return wrkDetl.getZpallet();
            }
        }
        return null;
    }
 
    private Date resolveCreateTime(WrkMast wrkMast) {
        if (!Cools.isEmpty(wrkMast.getCrnEndTime())) {
            return wrkMast.getCrnEndTime();
        }
        if (!Cools.isEmpty(wrkMast.getModiTime())) {
            return wrkMast.getModiTime();
        }
        if (!Cools.isEmpty(wrkMast.getIoTime())) {
            return wrkMast.getIoTime();
        }
        return new Date();
    }
 
    private Date resolveStartTime(WrkMast wrkMast) {
        if (!Cools.isEmpty(wrkMast.getCrnStrTime())) {
            return wrkMast.getCrnStrTime();
        }
        if (!Cools.isEmpty(wrkMast.getPlcStrTime())) {
            return wrkMast.getPlcStrTime();
        }
        if (!Cools.isEmpty(wrkMast.getIoTime())) {
            return wrkMast.getIoTime();
        }
        return new Date();
    }
 
    private String formatDate(Date date) {
        if (date == null) {
            return null;
        }
        return new SimpleDateFormat(DATE_TIME_PATTERN).format(date);
    }
 
    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_REPORT_FINISHED_WRK_STS);
            wrkMast.setLogMk(ERP_REPORT_SUCCESS_FLAG);
            wrkMast.setLogErrMemo(null);
            wrkMast.setLogErrTime(null);
        } else {
            wrkMast.setLogErrMemo(truncate(errorMsg, 500));
            wrkMast.setLogErrTime(now);
            if (retryTimes >= ERP_REPORT_MAX_RETRY_TIMES || !countCurrentAttempt) {
                wrkMast.setWrkSts(ERP_REPORT_FINISHED_WRK_STS);
                wrkMast.setLogMk(ERP_REPORT_FAIL_FLAG);
            } else {
                wrkMast.setWrkSts(ERP_REPORT_PENDING_WRK_STS);
                wrkMast.setLogMk(ERP_REPORT_PENDING_FLAG);
            }
        }
        if (!wrkMastService.updateById(wrkMast)) {
            throw new IllegalStateException("update outbound erp 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 erpOutAddress;
        }
        if (erpOutAddress == null) {
            return erpUrl;
        }
        if (erpUrl.endsWith("/") && erpOutAddress.startsWith("/")) {
            return erpUrl + erpOutAddress.substring(1);
        }
        if (!erpUrl.endsWith("/") && !erpOutAddress.startsWith("/")) {
            return erpUrl + "/" + erpOutAddress;
        }
        return erpUrl + erpOutAddress;
    }
}