#
18516761980
2022-07-25 2c37b04bc0e5e2eae772166f514ff67113668f17
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package com.slcf.controller;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
 
import com.alibaba.excel.EasyExcel;
import com.slcf.controller.param.SyncStockParam;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.EntityManagerFactoryUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
 
import com.slcf.pojo.UserBean;
import com.slcf.pojo.WaitPakInBean;
import com.slcf.bean.LocDetailCondition;
import com.slcf.bean.LocationCondition;
import com.slcf.pojo.LocDetailBean;
import com.slcf.pojo.LocationBean;
import com.slcf.pojo.SysLogBean;
import com.slcf.service.LocDetailService;
import com.slcf.service.LocationService;
import com.slcf.service.RoleService;
import com.slcf.service.SysLogService;
import com.slcf.util.AuthorityCode;
import com.slcf.util.Constants;
 
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;
 
/**
 * 库位管理控制器层
 * @author admin
 * @date 2018年11月13日
 */
@Controller
@RequestMapping("/stock")
public class StockController {
 
    @Resource
    LocationService locationService;
    @Autowired
    LocDetailService locDetailService;
    @Autowired
    SysLogService sysLogService;
    @Autowired
    RoleService roleService;
 
    Logger logger=Logger.getLogger(StockController.class);
    
    @RequestMapping("/goStock.action")
    public String goLocationPage(HttpServletRequest request){
        try {
            String rid = request.getSession().getAttribute("ROLEID").toString();
            String authCode = roleService.getAuthListByRoleMenu(Integer.parseInt(rid), 
                    AuthorityCode.StockCode);
            request.getSession().setAttribute("AUTHCODE",authCode);
            // 插入日志
            UserBean user = (UserBean) request.getSession().getAttribute("USER");
            SysLogBean sysLog = new SysLogBean();
            sysLog.setLogin_no(user.getUser_account());
            sysLog.setMachine_ip(request.getRemoteAddr());
            sysLog.setForm_no("goStock.action");
            sysLog.setTts_keyname("访问:库存查询");
            sysLog.setModi_user(user.getUser_account());
            sysLogService.insertSysLog(sysLog);
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return "stock";
    }
    
    /**
     * 分页查询所有
     * @return
     */
    @ResponseBody
    @RequestMapping("/locationList.action")
    public Map<String,Object> queryLocationListByPages(LocationCondition locationCon){                
        Map<String,Object>map=locationService.queryLocationList(locationCon);
        return map;
    }
    
    /**
     * 分页查询所有
     * @return
     */
    @ResponseBody
    @RequestMapping("/stkDetailList.action")
    public Map<String,Object> queryLocDetailListByPages(LocDetailCondition locDetailCon){
        if(locDetailCon.getLoc_no()==null || locDetailCon.getLoc_no().equals("")) {
            return null;
//            locationCon.setLoc_no("1");
        }
        Map<String,Object>map=locDetailService.queryLocDetailList(locDetailCon);
        return map;
    }
    
    /**
     * 根据id查询信息
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryLocationById.action")
    public LocationBean queryLocationById(@RequestParam("did")String id){
        try {
            return locationService.queryLocationById(id);
        }catch(Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }
    
    /**
     * 查询所有
     * @return
     */
    @ResponseBody
    @RequestMapping("/getLocation.action")
    public List<LocationBean> getLocation(){
        try {
            return locationService.getLocationList();
        }catch(Exception e) {
            System.out.println(e.getMessage());
            return null;
        }        
    }
    
    /**
     * 调用SAP库存同步接口,同步SAP库存到ASRS
     * @param loc_no
     * @return
     */
    @ResponseBody
    @RequestMapping("/syncStockFromSap.action")
    public Integer syncStockFromSap(@RequestParam("loc_no")String loc_no,
            @RequestParam("barcode")String barcode,HttpServletRequest request){
        int result = 0;
        try {
//            String sb = "{\"d\":{\"results\":[{\"__metadata\":{\"id\":\"httpTO_CDS(lgnum='385',lqnum='0000126742')\",\"uri\":\"http://d01aas25.sap.kraussmaffeigroup.net:8025/sap/opu/odata/SAP/Z_WM_H5_SRV/ZLQUA_AUTO_CDS(lgnum='385',lqnum='0000126742')\",\"type\":\"Z_WM_H5_SRV.ZLQUA_AUTO_CDSType\"},\"lgnum\":\"385\",\"lqnum\":\"0000126742\",\"lgtyp\":\"A01\",\"lgpla\":\"0400201\",\"matnr\":\"0028009\",\"maktx\":\"RECHTECK\",\"werks\":\"3885\",\"gesme\":\"5.000\",\"altme\":\"KGM\"}]}}";
            UserBean user=(UserBean)request.getSession().getAttribute("USER");
//            String httpUrl = Constants.SAP_URL + "/sap/opu/odata/SAP/Z_WM_H5_SRV/autoStorageSet";
            String httpUrl = Constants.SAP_URL + "/sap/opu/odata/SAP/Z_WM_H5_SRV/ZLQUA_AUTO_CDS";
            result = sendSyncStockCmd(httpUrl,loc_no,barcode);
//            result=waitPakInService.upWaitPakIn(waitPakIn);
            if(result>0) {
                // 插入日志
//                UserBean user = (UserBean) request.getSession().getAttribute("USER");
                SysLogBean sysLog = new SysLogBean();
                sysLog.setLogin_no(user.getUser_account());
                sysLog.setMachine_ip(request.getRemoteAddr());
                sysLog.setForm_no("upWaitPakIn.action");
                sysLog.setTts_keyname("同步SAP库存到ASRS:" + loc_no);
                sysLog.setModi_user(user.getUser_account());
                sysLogService.insertSysLog(sysLog);
            }
        }catch(Exception e) {
            System.out.println(e.getMessage());
        }
        return result;
    }
 
    /**
     * 调用SAP库存同步接口,同步SAP库存到ASRS
     * @param loc_no
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/syncStocksFromSap.action", method = RequestMethod.POST)
    public String syncStocksFromSap(@RequestBody List<SyncStockParam> params, HttpServletRequest request){
        StringBuilder res = new StringBuilder();
        int result = 0;
        int success = 0;
        int total = 0;
        try {
            if (params != null && params.size()>0) {
                for (SyncStockParam param : params) {
                    total ++;
                    String sb = "{\"d\":{\"results\":[{\"__metadata\":{\"id\":\"httpTO_CDS(lgnum='385',lqnum='0000126742')\",\"uri\":\"http://d01aas25.sap.kraussmaffeigroup.net:8025/sap/opu/odata/SAP/Z_WM_H5_SRV/ZLQUA_AUTO_CDS(lgnum='385',lqnum='0000126742')\",\"type\":\"Z_WM_H5_SRV.ZLQUA_AUTO_CDSType\"},\"lgnum\":\"385\",\"lqnum\":\"0000126742\",\"lgtyp\":\"A01\",\"lgpla\":\"0400201\",\"matnr\":\"0028009\",\"maktx\":\"RECHTECK\",\"werks\":\"3885\",\"gesme\":\"5.000\",\"altme\":\"KGM\"}]}}";
                    UserBean user=(UserBean)request.getSession().getAttribute("USER");
                    String httpUrl = Constants.SAP_URL + "/sap/opu/odata/SAP/Z_WM_H5_SRV/ZLQUA_AUTO_CDS";
                    result = sendSyncStockCmd(httpUrl,param.getLocNo(),param.getBarcode());
//                    result=waitPakInService.upWaitPakIn(waitPakIn);
                    if(result>0) {
                        // 插入日志
//                        UserBean user = (UserBean) request.getSession().getAttribute("USER");
                        SysLogBean sysLog = new SysLogBean();
                        sysLog.setLogin_no(user.getUser_account());
                        sysLog.setMachine_ip(request.getRemoteAddr());
                        sysLog.setForm_no("upWaitPakIn.action");
                        sysLog.setTts_keyname("同步SAP库存到ASRS:" + param.getBarcode());
                        sysLog.setModi_user(user.getUser_account());
                        sysLogService.insertSysLog(sysLog);
                        success ++ ;
                    } else {
                        res.append(param.getLocNo()).append(",");
                    }
                }
            }
//
        }catch(Exception e) {
            System.out.println(e.getMessage());
        }
        res.insert(0, "Number Of FAIL: " + (total - success) + "\n\n");
        res.insert(0, "Number Of SUCCESS: " + (success) + "\n\n");
        res.insert(0, "Processing is complete!\n\n");
        if (res.length() > 0) {
            res.append("location synchronization failure!");
        } else {
            res.append("synchronization success");
        }
        return res.toString();
    }
 
//    @RequestMapping(value = "/sync/excel/file/import.action", method = RequestMethod.POST)
//    @ResponseBody
//    public String matCodeImport(MultipartFile file) throws IOException, InterruptedException {
//        MatCodeExcelListener listener = new MatCodeExcelListener(getUserId());
//        EasyExcel.read(file.getInputStream(), MatCodeExcel.class, listener).sheet().doRead();
//        System.out.println(file.getOriginalFilename());
//        return "ok";
//    }
 
 
    /**
     * 调用sap接口完成ASRS库存更新
     */
    private int sendSyncStockCmd(String httpUrl,String loc_no,String barcode) {
        int result = 0;
        String input = Constants.SAP_USER + ":" + Constants.SAP_PASSWORD;//"ZHANGX:654321";
        BASE64Encoder base = new BASE64Encoder();
        String encodedPassword;
        try {
            encodedPassword = base.encode(input.getBytes("UTF-8"));
//            httpUrl += "?$filter=lgnum eq '385' and lgtyp eq 'A01' and lgpla eq '" + loc_no + "'";
            //"?$filter=lgnum%20eq%20%27385%27"
//            String filter = java.net.URLEncoder.encode("?$filter=lgnum eq '385'", "utf-8");
//            httpUrl += "?$filter=lgnum%20eq%20%27385%27%20";
            //空格20%,单引号27%
//            String filter1 = "?$filter=lgnum%20eq%20%27385%27%20and20%lgtyp%20eq%20%27A01%27";//20%and20%lgpla20%eq%20%27" + loc_no + "27%";
            String filter  = "?$filter=lgnum%20eq%20%27385%27%20and%20lgtyp%20eq%20%27A01%27%20and%20lgpla%20eq%20%27" + loc_no + "%27%20";
            httpUrl += filter;
            URL url1 = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", "Basic " + encodedPassword);
            connection.setRequestProperty("Content-Type","application/json");
            connection.setRequestProperty("Accept","application/json");
            connection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");
//            connection.setRequestProperty("Accept-Encoding","gzip, deflate");
            connection.setRequestProperty("x-csrf-token","Fetch");
 
            //读取响应
            InputStream instream = connection.getInputStream();
            String sb = IOUtils.toString(instream,"utf-8");
//            BufferedReader reader = new BufferedReader(new InputStreamReader(
//                    connection.getInputStream(),"utf-8"));
//            String lines;
//            StringBuffer sb = new StringBuffer("");
//            while ((lines = reader.readLine()) != null) {
//                lines = new String(lines.getBytes(), "utf-8");
//                sb.append(lines);
//            }
            logger.error("syncStocksFromSap---同步库存返回数据" + sb.toString());
            //解析json,更新库存
            JSONObject json = JSONObject.fromObject(sb.toString());
            String d = json.get("d").toString();
            JSONObject jsonItem = JSONObject.fromObject(d);
            String results = jsonItem.get("results").toString();
            JSONArray array = JSONArray.fromObject(results);
 
            result = locDetailService.delLocDetailByLocNo(loc_no);
            if(array.size()>0) {
                for(int i=0;i<array.size();i++){
                    JSONObject job = array.getJSONObject(i);
                    String matnr = job.get("matnr").toString();
                    String maktx = job.get("maktx").toString();
                    String werks = job.get("werks").toString();
                    double gesme = job.get("gesme").toString().equals("")?0:Double.parseDouble(job.get("gesme").toString());
                    String altme = job.get("altme").toString();
                    
                    LocDetailBean locDetl = new LocDetailBean();
//                    logger.error("syncStocksFromSap---插入数据" + matnr+"-"+maktx+"-"+werks+"-"+gesme+"-"+altme);
                    locDetl.setLoc_no(loc_no);
                    locDetl.setMatnr(matnr);
                    locDetl.setLgnum("385");
                    locDetl.setTbnum(1);
                    locDetl.setTbpos(1);
                    locDetl.setZmatid("1");
                    locDetl.setMaktx(maktx);
                    locDetl.setWerks(werks);
                    locDetl.setAnfme(gesme);
                    locDetl.setAltme(altme);
                    if(barcode == null || "".equals(barcode)) {
                        LocationBean locationBean = locationService.queryLocationById(loc_no);
                        barcode = locationBean.getBarcode();
                    }
                    locDetl.setZpallet(barcode);
                    locDetl.setBname("");
                    result = locDetailService.insertLocDetail(locDetl);
//                    logger.error("syncStocksFromSap---插入结果" + result);
 
                    if(result<=0) {
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("sendSyncStockCmd Error----" + e.getMessage());
            System.out.println(e.getMessage());
        }
        return result;
    }
    
}