ouyj 3 недель назад
Родитель
Сommit
d79191dc3b

+ 97 - 0
src/main/contract/com/yw/contract/common/sync/mes/MesCommonHelper.java

@@ -1,6 +1,8 @@
 package com.yw.contract.common.sync.mes;
 
 import com.yw.contract.contract.model.ContractCompany;
+import com.yw.contract.contract.model.ContractInfo;
+import com.yw.contract.contract.model.ContractMaterial;
 import com.yw.contract.contract.model.ContractPurchaseDetail;
 import com.yw.contract.contract.model.ContractPurchaseForm;
 import com.yw.contract.contract.model.ContractPurchaseOrder;
@@ -18,6 +20,7 @@ import org.springframework.util.ObjectUtils;
 
 import java.io.IOException;
 import java.util.ArrayList;
+import java.util.Date;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -608,4 +611,98 @@ public class MesCommonHelper  extends MesHelper{
         }
         return null;
     }
+    
+    /**
+     * 同步销售合同到MES销售订单
+     * @param contractInfo 合同信息
+     * @param contractMaterialList 合同物料明细
+     * @return MES返回的结果
+     * @throws Exception
+     */
+    public JSONObject syncSaleOrderToMes(ContractInfo contractInfo, List<ContractMaterial> contractMaterialList) throws Exception {
+        Map<String, Object> dats = new HashMap<>();
+        
+        // 设置销售订单基本信息
+        dats.put("clientCode", contractInfo.getSupplierCode()); // supplierCode对应clientCode
+        dats.put("clientName", contractInfo.getSupplierName()); // supplierName对应clientName
+        dats.put("salseDate", new Date());
+        dats.put("status", "CONFIRMED"); // 设置为确认状态
+        dats.put("contractId", contractInfo.getUniversalid());
+        dats.put("contractNumber", contractInfo.getContract_number());
+        
+        // 设置物料明细
+        if(!ObjectUtils.isEmpty(contractMaterialList)){
+            List<Map<String,Object>> details = new ArrayList<>();
+            for(ContractMaterial material : contractMaterialList){
+                Map<String, Object> detailMap = new HashMap<>();
+                detailMap.put("itemCode", material.getItemCode());
+                detailMap.put("itemName", material.getItemName());
+                detailMap.put("specification", material.getSpecification());
+                detailMap.put("measureName", material.getMeasureName());
+                detailMap.put("quantityOrder", material.getQty());
+                detailMap.put("price", material.getPrice());
+                detailMap.put("priceTax", material.getPriceTax());
+                detailMap.put("cess", material.getCess());
+                
+                // 计算含税总金额:数量 * 单价 * (1 + 税率%),空值默认为0
+                double qty = material.getQty() != null ? material.getQty().doubleValue() : 0;
+                double price = material.getPrice() != null ? material.getPrice().doubleValue() : 0;
+                double cess = material.getCess() != null ? material.getCess().doubleValue() : 0;
+                double totalPrice = qty * price * (1 + cess * 0.01);
+                detailMap.put("totalPrice", Math.round(totalPrice * 100.0) / 100.0); // 保留两位小数
+                
+                //detailMap.put("status", "0");
+                details.add(detailMap);
+            }
+            dats.put("wmSaleOrderLineList", details);
+        }
+        
+        Request request = postRequest(SyncConstant.SALEORDER_ADD_URL, dats);
+        try {
+            OkHttpClient client = new OkHttpClient().newBuilder().build();
+            Response response = client.newCall(request).execute();
+            if (response.isSuccessful()) {
+                if(response.body()!=null) {
+                    String resp = response.body().string();
+                    
+                    // 先尝试使用公共的checkResp处理(处理401等通用逻辑)
+                    try {
+                        int isResp = checkResp(resp);
+                        if(isResp == 0){
+                            return syncSaleOrderToMes(contractInfo, contractMaterialList);
+                        }
+                        // checkResp成功,返回结果
+                        return new JSONObject(resp);
+                    } catch (Exception e) {
+                        // checkResp抛出异常,尝试获取MES返回的具体错误信息
+                        try {
+                            JSONObject json = new JSONObject(resp);
+                            String msg = json.optString("msg", "同步销售订单失败");
+                            LogUtil.info("同步销售订单失败:" + msg);
+                            // 构造错误响应,而不是抛出异常
+                            JSONObject errorResp = new JSONObject();
+                            errorResp.put("code", json.optInt("code", 500));
+                            errorResp.put("msg", msg);
+                            return errorResp;
+                        } catch (Exception ex) {
+                            // 如果解析失败,构造通用错误响应
+                            JSONObject errorResp = new JSONObject();
+                            errorResp.put("code", 500);
+                            errorResp.put("msg", e.getMessage());
+                            return errorResp;
+                        }
+                    }
+                }else{
+                    System.out.println("请求成功,没有数据返回");
+                }
+            } else {
+                LogUtil.info(response.body().string());
+                throw new Exception("同步销售订单到MES失败");
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+            throw e;
+        }
+        return null;
+    }
 }

+ 1 - 0
src/main/contract/com/yw/contract/common/sync/mes/SyncConstant.java

@@ -22,4 +22,5 @@ public class SyncConstant {
     public final static String PURCHASE_INFO_URL = "/mes/wm/purchase/";
     public final static String ITEMRECPT_INFO_URL = "/mes/wm/itemrecpt/getInfoAndLines/";
     public final static String CLIENT_LIST_URL = "/mes/md/client/list";
+    public final static String SALEORDER_ADD_URL = "/mes/wm/saleorder/addFromOa";
 }

+ 79 - 0
src/main/contract/com/yw/contract/contract/action/ContractEntryAction.java

@@ -1,5 +1,6 @@
 package com.yw.contract.contract.action;
 
+import java.io.IOException;
 import java.io.PrintWriter;
 import java.io.UnsupportedEncodingException;
 import java.math.BigDecimal;
@@ -129,6 +130,8 @@ public class ContractEntryAction extends ContractFlowAction {
 			this.path = toSelectClient(request, response);
 		} else if ("clientList".equals(task)) {
 			this.path = clientList(request, response);
+		} else if ("syncSaleOrderToMes".equals(task)) {
+			this.path = syncSaleOrderToMes(request, response);
 		}
 	}
 
@@ -1442,5 +1445,81 @@ public class ContractEntryAction extends ContractFlowAction {
 	public void setFlowTitle(String flowTitle) {
 		this.flowTitle = flowTitle;
 	}
+	
+	/**
+	 * 同步销售合同到MES销售订单
+	 * @param request
+	 * @param response
+	 * @return
+	 */
+	private String syncSaleOrderToMes(HttpServletRequest request, HttpServletResponse response) throws Exception {
+		ApplicationContext cxt = AppSession.getApplicationContext();
+		contractEntryService = (ContractEntryService) cxt.getBean("contractEntryService");
+		
+		try {
+			// 获取合同ID
+			String universalid = request.getParameter("universalid");
+			if (StringUtil.isEmpty(universalid)) {
+				this.addAjaxError("合同ID不能为空!", response);
+				return this.PATH_AJAX;
+			}
+			
+			Long contractId = Long.valueOf(universalid);
+			
+			// 获取合同信息
+			ContractInfo contractInfo = contractEntryService.toEditContractEntry(contractId, oasession);
+			if (contractInfo == null) {
+				this.addAjaxError("合同不存在!", response);
+				return this.PATH_AJAX;
+			}
+			
+			// 检查是否为销售合同(contract_type=1)
+			if (contractInfo.getContract_type() == null || contractInfo.getContract_type() != 1L) {
+				this.addAjaxError("只有销售合同才能同步到MES!", response);
+				return this.PATH_AJAX;
+			}
+			
+			// 检查是否已经同步过
+			if (StringUtils.isNotEmpty(contractInfo.getOrderNumber())) {
+				this.addAjaxError("该合同已同步到MES,订单编号:" + contractInfo.getOrderNumber(), response);
+				return this.PATH_AJAX;
+			}
+			
+			// 获取合同物料明细
+			List<ContractMaterial> contractMaterialList = contractEntryService.getContractMaterialListByContractId(contractId);
+			if (ObjectUtils.isEmpty(contractMaterialList)) {
+				this.addAjaxError("合同没有物料明细,无法同步!", response);
+				return this.PATH_AJAX;
+			}
+			
+			// 调用MES接口同步
+			MesCommonHelper mesHelper = new MesCommonHelper();
+			mesHelper.login(); // 先登录MES
+			
+			org.json.JSONObject result = mesHelper.syncSaleOrderToMes(contractInfo, contractMaterialList);
+			
+			if (result != null && result.has("code") && result.getInt("code") == 200) {
+				// 同步成功,获取返回的订单编号
+				JSONObject data = result.getJSONObject("data");
+				String orderCode = data.getString("orderCode");
+				
+				// 更新合同的orderNumber字段
+				contractInfo.setOrderNumber(orderCode);
+				contractEntryService.editContractEntry(contractInfo);
+				
+				this.addAjaxInfo("同步成功!MES销售订单编号:" + orderCode, response);
+			} else {
+				// MES返回业务错误(如合同已存在)
+				String msg = result != null ? result.optString("msg", "同步失败") : "同步失败";
+				this.addAjaxError("同步到MES失败:" + msg, response);
+			}
+			
+		} catch (Exception e) {
+			e.printStackTrace();
+			this.addAjaxError("同步异常:" + e.getMessage(), response);
+		}
+		
+		return this.PATH_AJAX;
+	}
 
 }

+ 7 - 6
src/main/contract/com/yw/contract/contract/dao/ContractEntryDaoImpl.java

@@ -500,14 +500,15 @@ public class ContractEntryDaoImpl extends BaseDao implements ContractEntryDao {
 		String delsql = "DELETE FROM contract_relation WHERE contractid = ? OR contract_main_relation = ? ";
 		jdbcTemplate.update(delsql, new Object[] { info.getUniversalid().toString(), info.getUniversalid().toString() });
 		String relation_id = info.getRelation_ids();
-		String[] relation_ids = relation_id.split(",");
-		if (relation_ids.length > 0 && !"".equals(relation_ids[0])) {
-			for (int i = 0; i < relation_ids.length; i++) {
-				info.setContract_main_relation(relation_ids[i]);
-				this.addContractMainRelation(info);
+		if(StringUtils.isNotEmpty(relation_id)){
+			String[] relation_ids = relation_id.split(",");
+			if (relation_ids.length > 0 && !"".equals(relation_ids[0])) {
+				for (int i = 0; i < relation_ids.length; i++) {
+					info.setContract_main_relation(relation_ids[i]);
+					this.addContractMainRelation(info);
+				}
 			}
 		}
-
 	}
 
 	@Override

+ 26 - 0
src/main/webapp/yw/contract/contractEntryList.jsp

@@ -83,6 +83,12 @@
 												+ row.universalid
 												+ ')\">合同信息</a>&nbsp;';
 											if(row.lFormInsId){
+												// contract_type为1时(销售合同),显示同步销售订单按钮
+												if(row.contract_type == 1 && !row.orderNumber){
+													html += '<a href="#" onclick="syncSaleOrderToMes('
+														+ row.universalid
+														+ ')\">同步销售订单</a>&nbsp;';
+												}
 												// contract_type为1时,不显示生成采购订单和合同跟踪按钮
 												if(row.contract_type != 1 && !row.orderNumber){
 													html += '<a href=\"#\" onclick=\"createPurchaseOrder('
@@ -312,6 +318,26 @@ function createPurchaseOrderProcess(data){
 		} 
 	}
 }
+
+function syncSaleOrderToMes(id){
+	if (window.confirm("确定要同步该销售合同到MES吗?")){ 
+		$.ligerDialog.waitting('正在同步到MES,请稍候...');
+		var param={'universalid':id};
+		sendAsyncAjax(param,"contractEntry.do?task=syncSaleOrderToMes",'json',syncSaleOrderProcess);
+	}
+}
+
+function syncSaleOrderProcess(data){
+	$.ligerDialog.closeWaitting();
+	searchByKword();
+	if(data.success!=null){
+		$.ligerDialog.success(data.success);
+	}else if(data.error!=null){
+		$.ligerDialog.error(data.error);
+	}else{
+		$.ligerDialog.error("同步失败!");
+	}
+}
 </script>
 <style type="text/css">
 body {

+ 26 - 0
src/main/webapp/yw/contract/contractMyLaunchList.jsp

@@ -367,6 +367,12 @@
 												+ row.universalid
 												+ ')\">合同信息</a>&nbsp;';
 											if(row.lFormInsId){
+												// contract_type为1时(销售合同),显示同步销售订单按钮
+												if(row.contract_type == 1 && !row.orderNumber){
+													html += '<a href="#" onclick="syncSaleOrderToMes('
+														+ row.universalid
+														+ ')\">同步销售订单</a>&nbsp;';
+												}
 												// contract_type为1时,不显示生成采购订单和合同跟踪按钮
 												if(row.contract_type != 1 && !row.orderNumber){
 													html += '<a href=\"#\" onclick=\"createPurchaseOrder('
@@ -567,6 +573,26 @@ function createPurchaseOrderProcess(data){
 		} 
 	}
 }
+
+function syncSaleOrderToMes(id){
+	if (window.confirm("确定要同步该销售合同到MES吗?")){ 
+		$.ligerDialog.waitting('正在同步到MES,请稍候...');
+		var param={'universalid':id};
+		sendAsyncAjax(param,"contractEntry.do?task=syncSaleOrderToMes",'json',syncSaleOrderProcess);
+	}
+}
+
+function syncSaleOrderProcess(data){
+	$.ligerDialog.closeWaitting();
+	searchByKword();
+	if(data.success!=null){
+		$.ligerDialog.success(data.success);
+	}else if(data.error!=null){
+		$.ligerDialog.error(data.error);
+	}else{
+		$.ligerDialog.error("同步失败!");
+	}
+}
 </script>
 <style type="text/css">
 body {