浏览代码

优化打印订单功能。

xian 4 年之前
父节点
当前提交
36d02714ff

+ 3 - 0
watero-rst-interface/src/main/java/com/iamberry/rst/faces/cm/SalesOrderService.java

@@ -623,4 +623,7 @@ public interface SalesOrderService {
    *查询快递策略店铺项
    */
   List<StrategyStore> selectStrategyStore(Integer strategyId);
+
+  int printOrder(List<SalesOrder> list, Integer currAdmin);
+
 }

+ 2 - 2
watero-rst-service/pom.xml

@@ -48,8 +48,8 @@
                 <artifactId>maven-compiler-plugin</artifactId>
                 <version>3.3</version>
                 <configuration>
-                    <source>1.7</source>
-                    <target>1.7</target>
+                    <source>1.8</source>
+                    <target>1.8</target>
                 </configuration>
             </plugin>
         </plugins>

+ 29 - 0
watero-rst-service/src/main/java/com/iamberry/rst/service/cm/SalesOrderServiceImpl.java

@@ -20,6 +20,7 @@ import com.iamberry.rst.faces.cm.SalesOrderService;
 import com.iamberry.rst.faces.cm.StoreInfoService;
 import com.iamberry.rst.faces.order.EfastOrderService;
 import com.iamberry.rst.faces.order.OrderBatchService;
+import com.iamberry.rst.faces.order.OrderSyncLogService;
 import com.iamberry.rst.faces.order.OrderWarehouseService;
 import com.iamberry.rst.faces.product.ProductService;
 import com.iamberry.rst.service.cm.mapper.SalesOrderMapper;
@@ -89,6 +90,8 @@ public class SalesOrderServiceImpl implements SalesOrderService {
     private OrderBatchService orderBatchService;
     @Autowired
     private DeliveryStrategyMapper deliveryStrategyMapper;
+    @Autowired
+    private OrderSyncLogService orderSyncLogService;
 
     /**
      * 缓存订单项的前缀
@@ -2121,6 +2124,32 @@ public class SalesOrderServiceImpl implements SalesOrderService {
         return salesOrderMapper.selectStrategyStore(strategyId);
     }
 
+    @Override
+    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.REPEATABLE_READ)
+    public int printOrder(List<SalesOrder> list, Integer currAdmin) {
+        // 修改订单状态
+        list.forEach(o -> {
+            o.setSalesShippingStatus(1);
+            o.setSalesSendTime(new Date());
+            o.setSalesOldOrderStatus(11);
+            // 修改订单状态
+            if (salesOrderMapper.updateSalesOrder(o) <= 0) {
+                throw new RuntimeException("订单" + o.getSalesId() + "发货失败,请查询订单状态");
+            }
+            // 小亚通订单,调用接口发货
+            if (!orderSyncLogService.syncXYTOrderShip(new Integer[]{o.getSalesId()})) {
+                throw new RuntimeException("订单" + o.getSalesId() + "向小亚通发货失败,请查询订单状态");
+            }
+            // 添加订单追踪信息
+            OrderTracking orderTracking = new OrderTracking();
+            orderTracking.setAdminId(currAdmin);
+            orderTracking.setSalesDealCode(o.getSalesDealCode());
+            orderTracking.setTrackingDesc("打印订单");
+            salesOrderService.addTracking(orderTracking);
+        });
+        return list.size();
+    }
+
     /***
      * 计算金额
      * @param salesOrder

+ 197 - 201
watero-rst-web/src/main/java/com/iamberry/rst/controllers/order/AwaitSendController.java

@@ -39,10 +39,10 @@ import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.servlet.ModelAndView;
 
 import javax.servlet.http.HttpServletRequest;
-import java.io.File;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.charset.Charset;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.*;
@@ -281,6 +281,119 @@ public class AwaitSendController {
     }
 
     /**
+     * 创建电子面单上需要显示的产品名称
+     * @param salesOrderInfo
+     * @return
+     */
+    private String ctrOrderProduct(SalesOrder salesOrderInfo) {
+        /// 产品名称
+        SalesOrderItem item = new SalesOrderItem();
+        item.setItemOrderId(salesOrderInfo.getSalesId());
+        List<SalesOrderItem> items = salesOrderService.listSalesOrderItem(item);
+        StringBuilder goodName = new StringBuilder();
+        for (SalesOrderItem temp : items) {
+            goodName.append(temp.getProductAbbreviation()).append("(").append(temp.getColorAbbreviation()).append(")*").append(temp.getItemNum()).append(";");
+        }
+        // 维修编号
+        List<ComplaintDetectInfo> listDetect  = complaintDetectInfoService.listComplaintDetectBySalesId(salesOrderInfo.getSalesOrderId());
+        if(listDetect != null && listDetect.size() > 0){
+            goodName.append("<br>【维修编号:");
+            for(int i = 0; i< listDetect.size();i++ ){
+                ComplaintDetectInfo detectInfo = listDetect.get(i);
+                if( i == 0){
+                    goodName.append(detectInfo.getDetectNumber());
+                }else{
+                    goodName.append(",").append(detectInfo.getDetectNumber());
+                }
+            }
+            goodName.append("】");
+        }
+        // 特殊需求
+        if ("DBL".equalsIgnoreCase(salesOrderInfo.getSalesPostFirm())) {
+            goodName.append("<重泡比8000已备案>");
+        }
+        // 打印日期
+        goodName.append("【D").append(DateTimeUtil.format(new Date(), "MMdd")).append("】");
+        return goodName.toString();
+    }
+
+    /**
+     * 处理请求第三方平台的Handler
+     * @param salesOrderInfo
+     * @param commodity
+     */
+    private Double henderProduct(SalesOrder salesOrderInfo, List<Map<String, Object>> commodity, String uuid) {
+        SalesOrderItem item = new SalesOrderItem();
+        item.setItemOrderId(salesOrderInfo.getSalesId());
+        List<SalesOrderItem> items = salesOrderService.listSalesOrderItem(item);
+        // 整个产品的重量
+        double colorIsWeight = 0.00;
+        int Goodsquantity = 0;
+        for (SalesOrderItem temp : items) {
+            if(temp.getColorIsWeight() != null){
+                colorIsWeight += temp.getColorIsWeight();
+            }
+            Goodsquantity += temp.getItemNum();
+        }
+        // 增加产品信息
+        Map<String, Object> product1 = new HashMap<String, Object>(3);
+        product1.put("GoodsName", uuid);
+        product1.put("Goodsquantity", Goodsquantity);
+        product1.put("GoodsWeight", colorIsWeight/1000);
+        commodity.add(product1);
+        return colorIsWeight;
+    }
+
+    /**
+     * 生成一个订单对应的UUID
+     * @param orderId
+     * @return
+     */
+    private String ctrOrderUUID(String orderId) {
+        String key = CACHE_PRODUCT_NAME_TO_UUID_NAME + orderId;
+        String uuid = RedisUtils.get(key);
+        if(uuid == null){
+            uuid = UUIDGenerator.getUUID().substring(0, 8);
+            RedisUtils.put(key,uuid);
+            RedisUtils.expire(key, DateTimeUtil.addDay(15));
+        }
+        return uuid;
+    }
+
+    /**
+     * 保存物流文件
+     * @param filePath
+     * @param text
+     * @param orderId
+     * @throws IOException
+     */
+    private void savePostFile(String filePath, String text, String orderId) throws IOException {
+        File dir = new File(filePath + File.separator + "send_order");
+        if (!dir.exists()) {
+            dir.mkdir();
+        }
+        File file = new File(dir.getAbsolutePath() + File.separator + orderId + ".txt");
+        if (!file.createNewFile()) {
+            throw new RuntimeException("创建文件失败");
+        }
+        FileChannel foChannel = null;
+        try {
+            byte[] jsonByte = text.getBytes("UTF-8");
+            ByteBuffer buffer = ByteBuffer.allocate(jsonByte.length);
+            buffer.put(jsonByte);
+            foChannel = new FileOutputStream(file).getChannel();
+            buffer.flip();
+            foChannel.write(buffer);
+        } catch (Exception e) {
+            LOGGER.error("", e);
+        } finally {
+            if (foChannel != null) {
+                foChannel.close();
+            }
+        }
+    }
+
+    /**
      * 打单发货,兼容多台打印机并发打印
      * @param orderId
      * @param salesId
@@ -325,10 +438,9 @@ public class AwaitSendController {
             return ResponseJson.getFAILURE().addResponseKeyValue("error","物流公司未设置对应的数据" + salesOrderInfo.getSalesPostFirm());
         }
 
-        //判断是否是京东订单  订单来源 2020年3月30日新增
+        // 判断是否是京东订单  订单来源 2020年3月30日新增
         if("jd".equalsIgnoreCase(salesOrderInfo.getSalesPostFirm())){
             StoreInfo storeInfo = storeInfoService.getStoreInfoById(salesOrderInfo.getSalesStoreId());
-
             if(storeInfo.getStoreName().contains("京东")){
                 eOrderRequestData.ExpType = "1";
                 eOrderRequestData.ThrOrderCode = salesOrderInfo.getSalesExOrderId();
@@ -341,21 +453,20 @@ public class AwaitSendController {
             }
         }
 
-
-        // 组装通用数据
+        /* 组装通用数据 */
         eOrderRequestData.OrderCode = salesOrderInfo.getSalesOrderId();
         eOrderRequestData.PayType = (3);
         eOrderRequestData.Cost = (0.00);
         eOrderRequestData.OtherCost = (0.0);
         eOrderRequestData.Remark = salesId.toString();
         eOrderRequestData.IsReturnPrintTemplate = 1;
-        // 收件人信息
+        /* 收件人信息 */
         String[] addrs = salesOrderInfo.getSalesAddressInfo().split(" ");
         if (addrs.length <= 3) {
             addrs = salesOrderInfo.getSalesAddressInfo().split("-");
         }
         String addrDetails = salesOrderInfo.getSalesAddressInfo().substring(addrs[0].length() + addrs[1].length() + addrs[2].length() + 3);
-        Map<String, Object> receiver = new HashMap<String, Object>();
+        Map<String, Object> receiver = new HashMap<String, Object>(7);
         receiver.put("Name", salesOrderInfo.getSalesAddressName());
         receiver.put("Tel", salesOrderInfo.getSalesAddressTel());
         receiver.put("ProvinceName", AddrUtil.dealProvince(addrs[0]));
@@ -364,8 +475,8 @@ public class AwaitSendController {
         receiver.put("Address", addrDetails);
         receiver.put("PostCode", salesOrderInfo.getSalesAddressPostcode());
         eOrderRequestData.Receiver = (receiver);
-        // 发件人信息
-        Map<String, Object> sender = new HashMap<String, Object>();
+        /* 发件人信息 */
+        Map<String, Object> sender = new HashMap<String, Object>(7);
         sender.put("Name", storeShip.getStoreShipName());
         sender.put("Tel", storeShip.getStoreShipTel());
         sender.put("ProvinceName", storeShip.getStoreShipProvince());
@@ -374,215 +485,100 @@ public class AwaitSendController {
         sender.put("Address", storeShip.getStoreShipAddress());
         sender.put("PostCode", "523660");
         eOrderRequestData.Sender = (sender);
-        // 产品信息
+        /* 产品信息 */
         List<Map<String, Object>> commodity = new ArrayList<>();
-        SalesOrderItem item = new SalesOrderItem();
-        item.setItemOrderId(salesOrderInfo.getSalesId());
-        List<SalesOrderItem> items = salesOrderService.listSalesOrderItem(item);
-        // 整个产品的重量
-        Double colorIsWeight = 0.00;
-        StringBuilder goodName = new StringBuilder();
-        int Goodsquantity = 0;
-        for (SalesOrderItem temp : items) {
-            goodName.append(temp.getProductAbbreviation())
-                    .append("(")
-                    .append(temp.getColorAbbreviation())
-                    .append(")*")
-                    .append(temp.getItemNum())
-                    .append(";");
-            if(temp.getColorIsWeight() != null){
-                colorIsWeight += temp.getColorIsWeight();
-            }
-            Goodsquantity += temp.getItemNum();
-        }
-        // 20190603增加需求:产品名称后面增加售后维修编号
-        if(salesOrderInfo.getComplaintDetectInfoList() != null && salesOrderInfo.getComplaintDetectInfoList().size() > 0){
-            goodName.append("<br>【维修编号:");
-           for(int i = 0; i< salesOrderInfo.getComplaintDetectInfoList().size();i++ ){
-               ComplaintDetectInfo detectInfo = salesOrderInfo.getComplaintDetectInfoList().get(i);
-               if( i == 0){
-                   goodName.append(detectInfo.getDetectNumber());
-               }else{
-                   goodName.append(",").append(detectInfo.getDetectNumber());
-               }
-           }
-           goodName.append("】");
-        }
-        if ("DBL".equalsIgnoreCase(salesOrderInfo.getSalesPostFirm())) {
-            goodName.append("重泡比8000已备案");
-        }
-        // 20181113增加需求:产品名称后面增加打印订单日期
-        goodName.append("【D").append(DateTimeUtil.format(new Date(), "MMdd")).append("】");
-        // 生成一个uuid对应订单的产品信息,因为第三方系统不会完整保存产品名称到电子面单,会导致无法拣货
-        String key = CACHE_PRODUCT_NAME_TO_UUID_NAME + orderId;
-        String uuid = RedisUtils.get(key);
-        if(uuid == null){
-            uuid = UUIDGenerator.getUUID().substring(0, 8);
-            RedisUtils.put(key,uuid);
-            RedisUtils.expire(key, DateTimeUtil.addDay(15));
-        }
-        // 增加产品信息
-        Map<String, Object> product1 = new HashMap<String, Object>();
-        product1.put("GoodsName", uuid);
-        product1.put("Goodsquantity", Goodsquantity);
-        // 计算产品重量deliver_statistics
-        product1.put("GoodsWeight", colorIsWeight/1000);
-        commodity.add(product1);
+        double colorIsWeight = henderProduct(salesOrderInfo, commodity, ctrOrderUUID(salesOrderInfo.getSalesOrderId()));
         eOrderRequestData.Commodity = (commodity);
         eOrderRequestData.Weight = (colorIsWeight/1000);
-        //如果订单是字母件则按照子母件方式传值
-       List<SalesOrder> orders = salesOrderService.listSublistCount(salesId);
-        if(logisticsInfo.getLogisticsIsLashSingle() == 1 && orders != null && orders.size() > 0){
-            eOrderRequestData.Quantity = orders.size()+1;
+
+        /* 当前快递是否支持子母件,如果支持,需要将子母件的内容传递到系统 */
+        List<SalesOrder> orders = salesOrderService.listSublistCount(salesId);
+        if(logisticsInfo.getLogisticsIsLashSingle() == 1 && orders.size() >= 1){
+            eOrderRequestData.Quantity = (orders.size()+1);
         }else{
             eOrderRequestData.Quantity = 1;
         }
 
-        //第三方发货,传入的id
-        Set<Integer> salesIdsset = new HashSet<Integer>();
-        Set<String> salesCodeSet = new HashSet<String>();
-        salesIdsset.add(salesOrderInfo.getSalesId());
-        salesCodeSet.add(salesOrderInfo.getSalesDealCode());
-
+        JSONObject jsonObject = null;
         try {
             // 向第三方系统【快递鸟】提交订单数据,第三方系统会检测订单是否重复
-            String json = OrderUtils.orderOnlineByJson(eOrderRequestData);
-            JSONObject jsonObject = JSONObject.parseObject(json);
-            boolean flag = jsonObject.getBoolean("Success");
-            if (flag) {
-
-                // 主订单发货 : 仅针对已经通知通知配货的订单(如果已发货,此处不修改对应的订单数据)
-                SalesOrder salesOrder = new SalesOrder();
-                salesOrder.setSalesPostNum(jsonObject.getJSONObject("Order").getString("LogisticCode"));
-                salesOrder.setSalesShippingStatus(1);
-                salesOrder.setSalesSendTime(new Date());
-                salesOrder.setSalesId(salesId);
-                salesOrder.setSalesOldOrderStatus(11);
-                Integer res = salesOrderService.updateSalesOrder(salesOrder);
-                if (res == null || res <= 0) {
-                    return ResponseJson.getFAILURE().addResponseKeyValue("error", "订单状态非通知配货,无法打印");
-                }
-
-                /*子母单 : 获取子单打印模板集合*/
-                JSONArray subPrintTemplates = jsonObject.getJSONArray("SubPrintTemplates");
-                if(logisticsInfo.getLogisticsIsLashSingle() == 1 && orders != null && orders.size() >= 1 && subPrintTemplates.size() >= 1){
-                    //获取子单物流单号集合
-                    JSONArray subOrders = jsonObject.getJSONArray("SubOrders");
-                    //替换子单产品名称
-                    JSONArray subTemplates = new JSONArray();
-                    // 整个产品的重量
-                    SalesOrderItem it = new SalesOrderItem();
-                    for(int i = 0 ;i < subPrintTemplates.size(); i++){
-                        String subTemplate = subPrintTemplates.getString(i);
-                        StringBuilder productName = new StringBuilder();
-                        it.setItemOrderId(orders.get(i).getSalesId());
-                        List<SalesOrderItem> its = salesOrderService.listSalesOrderItem(it);
-                        for (SalesOrderItem temp : its) {
-                            productName
-                                    .append(temp.getProductAbbreviation())
-                                    .append("(")
-                                    .append(temp.getColorAbbreviation())
-                                    .append(")*")
-                                    .append(temp.getItemNum())
-                                    .append(";");
-                        }
-                        //替换产品名
-                        //如果是京东订单则需直接根据订单id替换产品信息
-                        if("jd".equalsIgnoreCase(salesOrderInfo.getSalesPostFirm())){
-                            subTemplate = subTemplate.replace(salesId.toString(), "<font style=\"font-size:6px\">"+productName.toString()+"</font>");
-                        }else{
-                            subTemplate = subTemplate.replace(uuid, productName.toString());
-                        }
-
-
-                        //替换订单号
-                        subTemplate = subTemplate.replace(orderId, orders.get(i).getSalesOrderId());
-                        //替换备注
-                        subTemplate = subTemplate.replace(salesId.toString(), orders.get(i).getSalesId().toString());
-                        subTemplates.add(subTemplate);
-                        // 订单发货 : 仅针对已经通知通知配货的订单(如果已发货,此处不修改对应的订单数据)
-                        SalesOrder order = new SalesOrder();
-                        order.setSalesPostNum(subOrders.get(i).toString());
-                        order.setSalesShippingStatus(1);
-                        order.setSalesSendTime(new Date());
-                        order.setSalesId(orders.get(i).getSalesId());
-                        order.setSalesOldOrderStatus(11);
-                        Integer msg = salesOrderService.updateSalesOrder(order);
-                        salesIdsset.add(orders.get(i).getSalesId());
-                        salesCodeSet.add(orders.get(i).getSalesDealCode());
-                        if (msg == null || msg <= 0) {
-                            return ResponseJson.getFAILURE().addResponseKeyValue("error", "子订单状态非通知配货,无法打印");
-                        }
-                    }
-
-                    jsonObject.put("SubPrintTemplates",subTemplates);
-                }
-                /*子母单设置 end*/
-
-
-                // 替换母订单产品名称
-                //如果是京东订单则需直接根据订单id替换产品信息
-                if("jd".equalsIgnoreCase(salesOrderInfo.getSalesPostFirm())){
-                    jsonObject.put("PrintTemplate",jsonObject.get("PrintTemplate").toString().replace(salesId.toString(), "<font style=\"font-size:6px\">"+goodName.toString()+"</font>"));
-                    json = jsonObject.toString();
-                } else if("sto".equalsIgnoreCase(salesOrderInfo.getSalesPostFirm())) {
-                    jsonObject.put("PrintTemplate",jsonObject.get("PrintTemplate").toString().replace(salesId.toString(), goodName.toString()));
-                    json = jsonObject.toString();
-                }else{
-                    jsonObject.put("PrintTemplate",jsonObject.get("PrintTemplate").toString().replace(uuid, goodName.toString()));
-                    json = jsonObject.toString();
-                }
-
+            jsonObject = JSONObject.parseObject(OrderUtils.orderOnlineByJson(eOrderRequestData));
+            if (!jsonObject.getBoolean("Success")) {
+                // 获取电子面单失败
+                String reason = jsonObject.get("Reason").toString();
+                LOGGER.error("{} 获取电子面单失败,原因:{}", orderId, reason);
+                throw new RuntimeException(reason);
+            }
 
-                // 保存HTML
-                String filePath = request.getServletContext().getRealPath("/common/");
-                File dir = new File(filePath + File.separator + "send_order");
-                if (!dir.exists()) {
-                    dir.mkdir();
-                }
-                File file = new File(dir.getAbsolutePath() + File.separator + orderId + ".txt");
-                if (!file.createNewFile()) {
-                    return ResponseJson.getFAILURE().addResponseKeyValue("error", "创建文件失败");
-                }
-                FileWriter fileWriter = null;
-                try {
-                    fileWriter = new FileWriter(file, false);
-                    fileWriter.write(jsonObject.toString());
-                } catch (Exception e) {
-                    LOGGER.error("", e);
-                } finally {
-                    if (fileWriter != null) {
-                        fileWriter.close();
+            // 批量向Service提交变更的信息
+            List<SalesOrder> changeOrderList = new ArrayList<>(eOrderRequestData.Quantity + 1);
+            // 主订单发货 : 仅针对已经通知通知配货的订单(如果已发货,此处不修改对应的订单数据)
+            SalesOrder salesOrder = new SalesOrder();
+            salesOrder.setSalesPostNum(jsonObject.getJSONObject("Order").getString("LogisticCode"));
+            salesOrder.setSalesDealCode(salesOrderInfo.getSalesDealCode());
+            salesOrder.setSalesId(salesId);
+            changeOrderList.add(salesOrder);
+
+            /*子母单 : 获取子单打印模板集合*/
+            JSONArray subPrintTemplates = jsonObject.getJSONArray("SubPrintTemplates");
+            if(eOrderRequestData.Quantity > 1){
+                //获取子单物流单号集合
+                JSONArray subOrders = jsonObject.getJSONArray("SubOrders");
+                //替换子单产品名称
+                JSONArray subTemplates = new JSONArray();
+                for(int i = 0 ;i < subPrintTemplates.size(); i++){
+                    // 电子面单
+                    String subTemplate = subPrintTemplates.getString(i);
+                    // 组装电子面单上的产品名称
+                    String productName = ctrOrderProduct(orders.get(i));
+                    if("jd".equalsIgnoreCase(salesOrderInfo.getSalesPostFirm())){
+                        subTemplate = subTemplate.replace(salesId.toString(), "<font style=\"font-size:6px\">"+productName+"</font>");
+                    }else{
+                        subTemplate = subTemplate.replace(ctrOrderUUID(salesOrderInfo.getSalesOrderId()), productName);
                     }
+                    // 替换订单号
+                    subTemplate = subTemplate.replace(orderId, orders.get(i).getSalesOrderId());
+                    // 替换备注
+                    subTemplate = subTemplate.replace(salesId.toString(), orders.get(i).getSalesId().toString());
+
+                    // 订单发货 : 仅针对已经通知通知配货的订单(如果已发货,此处不修改对应的订单数据)
+                    SalesOrder order = new SalesOrder();
+                    order.setSalesPostNum(subOrders.get(i).toString());
+                    order.setSalesId(orders.get(i).getSalesId());
+                    order.setSalesDealCode(orders.get(i).getSalesDealCode());
+                    changeOrderList.add(order);
+                    // 将改变后的打印模板添加到对应的List中
+                    subTemplates.add(subTemplate);
                 }
+                // 将更改后的模板添加(自动覆盖以前的)
+                jsonObject.put("SubPrintTemplates",subTemplates);
+            }
+            /*子母单设置 end*/
 
-                //小亚通订单,调用接口发货
-                try{
-                    Integer[] saleIds = salesIdsset.toArray(new Integer[] {});
-                    boolean isShip = orderSyncLogService.syncXYTOrderShip(saleIds);
-                }catch (Exception e){
-                    LOGGER.error("小亚通发货接口调用失败");
-                    e.printStackTrace();
-                }
 
-                //添加操作跟踪信息
-                for (String aSalesCodeSet : salesCodeSet) {
-                    OrderTracking orderTracking = new OrderTracking();
-                    orderTracking.setAdminId(AdminUtils.getLoginAdminId());
-                    orderTracking.setSalesDealCode(aSalesCodeSet);
-                    orderTracking.setTrackingDesc("打印订单");
-                    salesOrderService.addTracking(orderTracking);
-                }
+            // 替换母订单产品名称
+            String goodName = ctrOrderProduct(salesOrderInfo);
+            if("jd".equalsIgnoreCase(salesOrderInfo.getSalesPostFirm())){
+                jsonObject.put("PrintTemplate",jsonObject.get("PrintTemplate").toString().replace(salesId.toString(), "<font style=\"font-size:6px\">"+goodName+"</font>"));
+            } else if("sto".equalsIgnoreCase(salesOrderInfo.getSalesPostFirm())) {
+                jsonObject.put("PrintTemplate",jsonObject.get("PrintTemplate").toString().replace(salesId.toString(), goodName));
+            }else{
+                jsonObject.put("PrintTemplate",jsonObject.get("PrintTemplate").toString().replace(ctrOrderUUID(salesOrderInfo.getSalesOrderId()), goodName));
+            }
 
-            } else {
-                // 获取电子面单失败
-                LOGGER.error("{} 获取电子面单失败,原因:{}", orderId, jsonObject.get("Reason"));
+            // 提交数据库
+            if (salesOrderService.printOrder(changeOrderList, AdminUtils.getLoginAdminId()) <= 0) {
+                throw new RuntimeException("订单发货失败,请核查");
             }
-            return ResponseJson.getSUCCESS().addResponseKeyValue("json", json);
+
+            // 保存HTML
+            savePostFile(request.getServletContext().getRealPath("/common/"), jsonObject.toJSONString(), salesOrderInfo.getSalesOrderId());
         } catch (Exception e) {
             LOGGER.error("", e);
             return ResponseJson.getFAILURE().addResponseKeyValue("error", e.getMessage());
         }
+        // 成功
+        return ResponseJson.getSUCCESS().addResponseKeyValue("json", jsonObject.toJSONString());
     }
 
     // 重新打印发货

+ 64 - 55
watero-rst-web/src/main/webapp/WEB-INF/views/order/salesOrder/list_wait_send_order.ftl

@@ -262,6 +262,7 @@
 </div>
 <#include "/base/page_util.ftl">
 <script type="text/javascript">
+    var selPrinter = -1;
     function toDoShow3(){
         //页面层
         layer.open({
@@ -345,55 +346,75 @@
                 success: function(data){
                     var res = $.parseJSON(data.returnMsg.json);
                     if (data.resultMsg && res.Success) {
+                        // 打印主订单
+                        let isFirst = true;
+                        let isOne = false;
                         if(mains != null){
                             var html = res.PrintTemplate;
                             $("#temp-print-order").html(html);
-                            LODOP.PRINT_INIT('打印订单' + $("#orderId").val());
+                            LODOP.PRINT_INIT('打印订单' + $("#orderId").val() + "_"+Math.ceil(Math.random()*1000000));
                             LODOP.SET_PRINT_PAGESIZE(0, 0, 0,"");
                             LODOP.ADD_PRINT_HTM("0mm","0mm","100%","100%", $("#temp-print-order").html());
                             LODOP.SELECT_PRINTER(true);
-                        }else{
-                            //打印子订单
+                            isFirst = false;
+                        }
+                        // 打印子订单
+                        if (isFirst && subs != null && subs.length > 0) {
                             var SubPrintTemplates = res.SubPrintTemplates;
                             var sus = new Array()
                             for (var i = 0; i < subs.length; i++) {
                                 sus[i] = SubPrintTemplates[subs[i]]
                             }
                             if(sus != null){
-                                sus.map(function (item,index,ary ) {
-                                   $("#temp-print-order").html(item);
-                                   var subPrintTemplate = $("#temp-print-order").html();
-                                   suPrint(subPrintTemplate);
-                                });
+                                $("#temp-print-order").html(sus[0]);
+                                LODOP.PRINT_INIT('打印订单' + $("#orderId").val() + "_1"+Math.ceil(Math.random()*1000000));
+                                LODOP.SET_PRINT_PAGESIZE(0, 0, 0,"");
+                                LODOP.ADD_PRINT_HTM("0mm","0mm","100%","100%", $("#temp-print-order").html());
+                                LODOP.SELECT_PRINTER(true);
                             }
-                            layer.msg("打印成功",{icon: 6,time:3000});
+                            isOne = true;
                         }
                         // 注意,选择打印机后,需要更改打印机事件,否则无法执行回调
-                        var spans = $("span");
-                        if(subs != null && subs.length > 0){
-                            for (var i = 0; i < spans.length; i++) {
-                                if ($(spans[i]).text() === "打印份数:") {
-                                    $(spans[i]).parent().next()[0].onclick = function () {
-                                        CLODOP.SelectBox.clickOK(false);
-                                        layer.msg("打印成功",{icon: 6,time:3000});
-                                        //打印子订单
-                                        var SubPrintTemplates = res.SubPrintTemplates;
-                                        var sus = new Array()
-                                        for (var i = 0; i < subs.length; i++) {
-                                            sus[i] = SubPrintTemplates[subs[i]]
-                                        }
-                                        if(sus != null){
-                                            sus.map(function (item,index,ary ) {
-                                                $("#temp-print-order").html(item);
-                                                var subPrintTemplate = $("#temp-print-order").html();
-                                                suPrint(subPrintTemplate);
-                                            });
-                                        }
-                                    };
+
+                        (function(res, isOne) {
+                            var spans = $("span");
+                            if(subs != null && subs.length > 0){
+                                for (var i = 0; i < spans.length; i++) {
+                                    if ($(spans[i]).text() === "打印份数:") {
+                                        $(spans[i]).parent().next()[0].onclick = function () {
+                                            CLODOP.SelectBox.clickOK(false);
+                                            selPrinter = CLODOP.SelectBox.selPrinter.value;
+                                            layer.msg("打印成功",{icon: 6,time:3000});
+                                            //打印子订单
+                                            var SubPrintTemplates = res.SubPrintTemplates;
+                                            var sus = new Array()
+                                            for (var i = 0; i < subs.length; i++) {
+                                                sus[i] = SubPrintTemplates[subs[i]]
+                                            }
+                                            if(sus != null){
+                                                (function(SubPrintTemplates, isOne) {
+                                                    if(SubPrintTemplates != null){
+                                                        SubPrintTemplates.map(function (item,index,ary ) {
+                                                            if (isFirst && index === 0) {
+                                                                return;
+                                                            }
+
+                                                            $("#temp-print-order").html(item);
+                                                            LODOP.PRINT_INIT('打印订单1'+index+Math.ceil(Math.random()*1000000));
+
+                                                            LODOP.SET_PRINTER_INDEX(selPrinter);
+                                                            LODOP.SET_PRINT_PAGESIZE(0, 0, 0,"");
+                                                            LODOP.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", $("#temp-print-order").html());
+                                                            LODOP.PRINT();
+                                                        });
+                                                    }
+                                                }(sus, isOne));
+                                            }
+                                        };
+                                    }
                                 }
                             }
-                        }
-
+                        }(res, isOne));
                     }
                 }
             });
@@ -415,6 +436,7 @@
                         var res = $.parseJSON(data.returnMsg.json);
                         var flag = true;
                         if (data.resultMsg && res.Success) {
+                            // 打印主订单
                             if (mains != null) {
                                 var html = res.PrintTemplate;
                                 $("#temp-print-order").html(html);
@@ -422,8 +444,9 @@
                                 LODOP.SET_PRINT_PAGESIZE(0, 0, 0, "");
                                 LODOP.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", $("#temp-print-order").html());
                                 flag = LODOP.PRINT();
-                            }else{
-                                //打印子订单
+                            }
+                            // 打印子订单
+                            if (subs != null && subs.length > 0) {
                                 var SubPrintTemplates = res.SubPrintTemplates;
                                 var sus = new Array()
                                 for (var i = 0; i < subs.length; i++) {
@@ -433,29 +456,15 @@
                                     sus.map(function (item,index,ary ) {
                                         $("#temp-print-order").html(item);
                                         var subPrintTemplate = $("#temp-print-order").html();
-                                        suPrint(subPrintTemplate);
+                                        LODOP.PRINT_INIT('打印订单' + $("#orderId").val() + "_2"+Math.ceil(Math.random()*1000000));
+                                        LODOP.SET_PRINT_PAGESIZE(0, 0, 0,"");
+                                        LODOP.ADD_PRINT_HTM("0mm","0mm","100%","100%", subPrintTemplate);
+                                        LODOP.PRINT();
                                     });
                                 }
-                                return;
-                            }
-                            if (flag) {
-                                layer.msg("打印成功", {icon: 6, time: 3000});
-                                //打印子订单
-                                if(subs != null && subs.length > 0) {
-                                    var SubPrintTemplates = res.SubPrintTemplates;
-                                    var sus = new Array()
-                                    for (var i = 0; i < subs.length; i++) {
-                                        sus[i] = SubPrintTemplates[subs[i]]
-                                    }
-                                    if(sus != null){
-                                        sus.map(function (item,index,ary ) {
-                                            $("#temp-print-order").html(item);
-                                            var subPrintTemplate = $("#temp-print-order").html();
-                                            suPrint(subPrintTemplate);
-                                        });
-                                    }
-                                }
                             }
+
+                            layer.msg("打印成功", {icon: 6, time: 3000});
                         }
                     }
                 });
@@ -516,7 +525,7 @@
                             "url" : "${path}/admin/salesOrder/getSalesOrderByPostNum",
                             async:false,
                             "success" : function(data) {
-                                if(data.returnCode != 200){
+                                if(data.returnCode !== 200){
                                     return;
                                 }
                                 let salesOrder = data.returnMsg.salesOrder;

+ 37 - 46
watero-rst-web/src/main/webapp/WEB-INF/views/order/salesOrder/print_order.ftl

@@ -93,6 +93,7 @@
         </div>
 
         <div id="temp-print-order" style="zoom:0.9;display:none"></div>
+        <div id="temp-print-order-list" style="display: none"></div>
 
         <div id="print-pageview-div" style="display: none"></div>
     </div>
@@ -183,14 +184,14 @@
                 success: function(data){
 
                     var tempObject = data;
-                    if ('string' == typeof(data)) {
+                    if ('string' === typeof(data)) {
                         tempObject = $.parseJSON(data);
                     }
                     if (tempObject.hasOwnProperty("error")) {
                         // 捕获系统级的错误(比如因为空指针抛出的Exception)
                         re_print(order, tempObject.error_msg, isIE, isFirst);
                     } else {
-                            if (data && data.returnCode && data.returnCode != 200) {
+                            if (data && data.returnCode && data.returnCode !== 200) {
                                 // 捕获业务级的操作(如订单的店铺没有绑定发货人信息)
                                 re_print(order, data.returnMsg.error, isIE, isFirst);
                             } else {
@@ -202,7 +203,6 @@
                                     var SubPrintTemplates = res.SubPrintTemplates;
                                     var SubOrders = res.SubOrders;
                                     printing(isIE, isFirst,SubPrintTemplates,SubOrders,order);
-
                                 }else {
                                     // 第三方接口错误
                                     re_print(order, res.Reason, isIE, isFirst);
@@ -215,24 +215,21 @@
 
 
         function printing(isIE, isFirst,SubPrintTemplates,SubOrders,order) {
+            let orderTemplate = $("#temp-print-order");
             LODOP.SET_PRINT_PAGESIZE(0, 0, 0, "");
-            LODOP.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", $("#temp-print-order").html());
+            LODOP.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", orderTemplate.html());
             if (isIE) {
                 // IE类浏览器,直接打印
                 if (LODOP.PRINT()) {
-                    if(SubPrintTemplates != null){
-                        SubPrintTemplates.map(function (item,index,ary ) {
-                            console.log(item);
-                            $("#temp-print-order").html(item);
-                            var subPrintTemplate = $("#temp-print-order").html();
-                            var orderid = SubOrders[i];
-                            /* (function(){
-                                            LODOP.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", subPrintTemplate);
-                                            LODOP.PRINT();
-                                        })();*/
-                            suPrint(subPrintTemplate);
-                        });
-                    }
+                    (function(SubPrintTemplates) {
+                        if(SubPrintTemplates != null){
+                            SubPrintTemplates.map(function (item,index,ary ) {
+                                orderTemplate.html(item);
+                                LODOP.PRINT_INIT('打印订单3'+index+Math.ceil(Math.random()*1000000));
+                                suPrint(orderTemplate.html());
+                            });
+                        }
+                    }(SubPrintTemplates));
                     $(order.find("td")[0]).html("<span style='color: blue'>打印完成</span>");
                     startPrint(isIE, false);
                 } else {
@@ -248,22 +245,21 @@
                     var spans = $("span");
                     for (var i = 0; i < spans.length; i++) {
                         if ($(spans[i]).text() === "打印份数:") {
+                            // 此处需要使用闭包
                             $(spans[i]).parent().next()[0].onclick = function () {
                                 CLODOP.SelectBox.clickOK(false);
                                 selPrinter = CLODOP.SelectBox.selPrinter.value;
-                                if(SubPrintTemplates != null){
-                                    SubPrintTemplates.map(function (item,index,ary ) {
-                                        console.log(item);
-                                        $("#temp-print-order").html(item);
-                                        var subPrintTemplate = $("#temp-print-order").html();
-                                        var orderid = SubOrders[i];
-                                        /* (function(){
-                                            LODOP.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", subPrintTemplate);
-                                            LODOP.PRINT();
-                                        })();*/
-                                        suPrint(subPrintTemplate);
-                                    });
-                                }
+                                (function(SubPrintTemplates) {
+                                    if(SubPrintTemplates != null){
+                                        SubPrintTemplates.map(function (item,index,ary ) {
+                                            orderTemplate.html(item);
+                                            LODOP.PRINT_INIT('打印订单1'+index+Math.ceil(Math.random()*1000000));
+                                            LODOP.SET_PRINTER_INDEX(selPrinter);
+                                            suPrint(orderTemplate.html());
+                                        });
+                                    }
+                                }(SubPrintTemplates));
+
                                 $(order.find("td")[0]).html("<span style='color: blue'>打印完成</span>");
                                 startPrint(isIE, false);
                             };
@@ -271,23 +267,19 @@
                     }
                 } else {
                     // 如果非第一次打印,则调用打印接口
+                    LODOP.PRINT_INIT('打印订单NOFirst_'+Math.ceil(Math.random()*10000));
                     LODOP.SET_PRINTER_INDEX(selPrinter);
                     if (LODOP.PRINT()) {
-                        /*startPrint(isIE, false);*/
-                        /*$(order.find("td")[0]).html("<span style='color: blue'>打印完成</span>");*/
-                        if(SubPrintTemplates != null){
-                            SubPrintTemplates.map(function (item,index,ary ) {
-                                console.log(item);
-                                $("#temp-print-order").html(item);
-                                var subPrintTemplate = $("#temp-print-order").html();
-                                var orderid = SubOrders[i];
-                                /*(function(){
-                                    LODOP.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", subPrintTemplate);
-                                    LODOP.PRINT();
-                                })();*/
-                                suPrint(subPrintTemplate);
-                            });
-                        }
+                        (function(SubPrintTemplates) {
+                            if(SubPrintTemplates != null){
+                                SubPrintTemplates.map(function (item,index,ary ) {
+                                    orderTemplate.html(item);
+                                    LODOP.PRINT_INIT('打印订单2'+index+Math.ceil(Math.random()*1000000));
+                                    LODOP.SET_PRINTER_INDEX(selPrinter);
+                                    suPrint(orderTemplate.html());
+                                });
+                            }
+                        }(SubPrintTemplates));
                         $(order.find("td")[0]).html("<span style='color: blue'>打印完成</span>");
                         startPrint(isIE, false);
                     } else {
@@ -300,7 +292,6 @@
         }
         //子单打印调用
         function suPrint(subPrintTemplate) {
-            console.log(subPrintTemplate);
             LODOP.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", subPrintTemplate);
             return LODOP.PRINT();
         }