Example #1
0
 public void run() {
   // TODO Auto-generated method stub
   Connection conn = null;
   try {
     conn = PoolHelper.getInstance().getConnection("shop");
     delivery(conn);
   } catch (Exception e) {
     try {
       if (conn != null && !conn.getAutoCommit()) conn.rollback();
       conn.setAutoCommit(true);
     } catch (SQLException e1) {
       // TODO Auto-generated catch block
       Log.error(username, "关闭数据库事务出错  " + e1.getMessage(), null);
     }
     Log.info(username, "发货线程错误: " + e.getMessage(), null);
   } finally {
     if (conn != null)
       try {
         conn.close();
       } catch (SQLException e) {
         // TODO Auto-generated catch block
         Log.error(username, "关闭数据库连接出错: " + e.getMessage(), null);
       }
     watch.countDown();
   }
 }
Example #2
0
  private void delivery(Connection conn) throws Exception {

    String sql =
        "select  a.sheetid,b.tid, upper(ltrim(rtrim(b.companycode))) companycode,"
            + "upper(ltrim(rtrim(b.outsid))) outsid from it_upnote a with(nolock), ns_delivery b with(nolock)"
            + "where a.sheettype=3 and a.sheetid=b.sheetid and a.receiver='"
            + Params.tradecontactid
            + "' and b.iswait=0";
    Vector vdeliveryorder = SQLHelper.multiRowSelect(conn, sql);
    Log.info(username, " 本次要处理的淘宝发货条数为: " + vdeliveryorder.size(), null);
    for (int i = 0; i < vdeliveryorder.size(); i++) {

      Hashtable hto = (Hashtable) vdeliveryorder.get(i);
      String sheetid = hto.get("sheetid") != null ? hto.get("sheetid").toString() : "";
      String orderid = hto.get("tid") != null ? hto.get("tid").toString() : "";
      String post_company = hto.get("companycode") != null ? hto.get("companycode").toString() : "";
      String post_no = hto.get("outsid") != null ? hto.get("outsid").toString() : "";
      // 如果物流公司为空则忽略处理
      if (post_company.trim().equals("")) {
        Log.warn(username, jobName + " 快递公司为空!订单号:" + orderid, null);
        continue;
      }

      // 如果物流公司为空则忽略处理
      if (post_no.trim().equals("")) {
        Log.warn(username, "快递单号为空!订单号:" + orderid, null);
        continue;
      }

      if (!StringUtil.isNumeric(orderid)) {
        sql =
            "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                + " where SheetID = '"
                + sheetid
                + "' and SheetType = 3";
        SQLHelper.executeSQL(conn, sql);

        sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

        SQLHelper.executeSQL(conn, sql);

        Log.warn(username, jobName + ",订单号【" + orderid + "】不全是数字!", null);
        continue;
      }
      if ("1".equals(Params.isJZ)) {
        sql = "select top 1 lbpdc from ns_customerorder where tid='" + orderid + "'";
        String isJz = SQLHelper.strSelect(conn, sql);
        if ("zj".equals(isJz)) { // 家装订单
          // jzSend(post_no,orderid,post_company,conn,sheetid);
          Log.info(username, "家装订单暂时不发货: 订单号: " + orderid, null);
        } else normalSend(post_no, orderid, post_company, conn, sheetid);
      } else normalSend(post_no, orderid, post_company, conn, sheetid);
    }
  }
Example #3
0
 @Override
 public void process() throws Exception {
   Document doc = DOMHelper.newDocument(this.getBizdata(), "gbk");
   Element ele = doc.getDocumentElement();
   Element dtcFlow = DOMHelper.getSubElementsByName(ele, "DTCFlow")[0];
   Element paymentElement = DOMHelper.getSubElementsByName(dtcFlow, "PAYMENT_INFO_FB")[0];
   String statusCode = DOMHelper.getSubElementVauleByName(paymentElement, "STATUS_CODE");
   String paymentNumber = DOMHelper.getSubElementVauleByName(paymentElement, "PAYMENT_NO");
   Log.info("支付单回执数据处理成功,支付号: " + paymentNumber + " 支付单状态码: " + statusCode);
 }
Example #4
0
  private void sendTradeInfo(List sheetids, Connection conn) throws Exception {
    Vector<Hashtable> tradeInfo = new Vector();
    String sql = "";
    boolean isSuccess = false;
    for (int i = 0; i < sheetids.size(); i++) {
      try {
        String sheetid = (String) sheetids.get(i);
        sql =
            "select tid,actiontime,operator,status,remark from ns_tradetrace where sheetid='"
                + sheetid
                + "'";
        tradeInfo = SQLHelper.multiRowSelect(conn, sql);
        for (Iterator it = tradeInfo.iterator(); it.hasNext(); ) {
          Hashtable tab = (Hashtable) it.next();
          isSuccess = sendSingleInfo(tab);
        }
        if (isSuccess) {
          sql =
              "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                  + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                  + " where SheetID = '"
                  + sheetid
                  + "' and SheetType = 6";
          SQLHelper.executeSQL(conn, sql);

          sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=6";

          SQLHelper.executeSQL(conn, sql);
          Log.info(username, "处理淘宝订单跟踪信息,sheetid:【" + sheetid + "】成功", null);
        } else {
          Log.info(username, "处理淘宝订单跟踪信息,sheetid:【" + sheetid + "】失败", null);
        }
      } catch (Exception e) {
        Log.error(username, "同步订单跟踪信息出错  " + e.getMessage(), null);
        continue;
      }
    }
  }
Example #5
0
 // ²éѯÉÌÆ·¿â´æ
 public static void queryItemStock() throws Exception {
   String goodsId = "";
   String skuId = "";
   String outerId = "";
   String service = "subSyncItemStockInfo";
   HashMap<String, String> map = new HashMap<String, String>();
   map.put("goodsId", goodsId);
   map.put("skuId", skuId);
   map.put("outerId", outerId);
   String bizData = new JSONObject(map).toString();
   String sign = JwUtil.makeSign(bizData);
   Map requestParams = JwUtil.makeRequestParams(bizData, service, appkey, format, sign);
   String result = CommHelper.sendRequest(url, requestParams, "");
   Log.info("result: " + result);
 }
Example #6
0
 // ²éѯ¶©µ¥×´Ì¬
 public static void queryOrderStatus() throws Exception {
   String orderCode = "";
   String platFormName = "";
   String shopName = "";
   String service = "subQueryOrderState";
   HashMap<String, String> map = new HashMap<String, String>();
   map.put("orderCode", orderCode);
   map.put("platFormName", platFormName);
   map.put("shopName", shopName);
   String bizData = new JSONObject(map).toString();
   String sign = JwUtil.makeSign(bizData);
   Map requestParams = JwUtil.makeRequestParams(bizData, service, appkey, format, sign);
   String result = CommHelper.sendRequest(url, requestParams, "");
   Log.info("result: " + result);
 }
Example #7
0
 private boolean sendSingleInfo(Hashtable tab) throws Exception {
   boolean isSuccess = false;
   String tidString = tab.get("tid").toString().trim();
   if (!StringUtils.isNumeric(tidString)) return true;
   Long tid = Long.parseLong(tidString);
   String actionTime = tab.get("actiontime").toString().trim().substring(0, 19);
   String operator = tab.get("operator").toString().trim();
   String status = tab.get("status").toString().trim();
   String remark = tab.get("remark").toString().trim();
   try {
     TaobaoClient client = new DefaultTaobaoClient(Params.url, Params.appkey, Params.appsecret);
     TmcMessageProduceRequest req = new TmcMessageProduceRequest();
     req.setTopic("taobao_jds_TradeTrace");
     Map<String, Object> map = new HashMap<String, Object>();
     map.put("action_time", actionTime);
     map.put("operator", operator);
     map.put("remark", remark);
     map.put("seller_nick", Params.sellernick);
     map.put("status", status);
     map.put("tid", tid);
     String contents = new JSONWriter().write(map);
     // Log.info("contents: " +contents);
     req.setContent(contents);
     TmcMessageProduceResponse rep = client.execute(req, Params.authcode);
     // Log.info("req: "+rep.getBody());
     if (rep.getIsSuccess()) {
       isSuccess = true;
       // Log.info("发送单条订单跟踪数据成功,订单号: "+tid+"状态: "+status);
     }
   } catch (Exception e) {
     Log.error(
         username,
         "发送单条订单跟踪数据出错,tid: '" + tid + ",status: '" + status + " " + e.getMessage(),
         null);
   }
   return isSuccess;
 }
Example #8
0
  public void run() {
    Log.info(jobname, "启动[" + jobname + "]模块");
    do {
      Connection connection = null;
      is_importing = true;
      try {
        connection =
            PoolHelper.getInstance().getConnection(com.wofu.ecommerce.taobao.Params.dbname);
        lasttime =
            PublicUtils.getConfig(
                connection,
                lasttimeconfvalue,
                Formatter.format(new Date(), Formatter.DATE_TIME_FORMAT));

        getRefundBillList(connection);
      } catch (Exception e) {
        try {
          if (connection != null && !connection.getAutoCommit()) connection.rollback();
        } catch (Exception e1) {
          Log.error(jobname, "回滚事务失败");
        }
        Log.error("105", jobname, Log.getErrorMessage(e));
      } finally {
        is_importing = false;
        try {
          if (connection != null) connection.close();
        } catch (Exception e) {
          Log.error(jobname, "关闭数据库连接失败");
        }
      }
      System.gc();
      long startwaittime = System.currentTimeMillis();
      while (System.currentTimeMillis() - startwaittime
          < (long) (com.wofu.ecommerce.taobao.Params.waittime * 1000))
        try {
          sleep(1000L);
        } catch (Exception e) {
          Log.warn(jobname, "系统不支持休眠操作, 作业将严重影响机器性能");
        }
    } while (true);
  }
Example #9
0
  public void run() {
    Log.info(jobname, "启动[" + jobname + "]模块");
    do {
      Connection connection = null;
      is_exporting = true;
      try {
        connection = PoolHelper.getInstance().getConnection(Params.dbname);

        delivery(connection);

        // modifiRemark(connection);

      } catch (Exception e) {
        try {
          if (connection != null && !connection.getAutoCommit()) connection.rollback();
        } catch (Exception e1) {
          Log.error(jobname, "回滚事务失败");
        }
        Log.error("105", jobname, Log.getErrorMessage(e));
      } finally {
        is_exporting = false;
        try {
          if (connection != null) connection.close();
        } catch (Exception e) {
          Log.error(jobname, "关闭数据库连接失败");
        }
      }
      System.gc();
      long startwaittime = System.currentTimeMillis();
      while (System.currentTimeMillis() - startwaittime < (long) (Params.waittime * 1000))
        try {
          sleep(1000L);
        } catch (Exception e) {
          Log.warn(jobname, "系统不支持休眠操作, 作业将严重影响机器性能");
        }
    } while (true);
  }
Example #10
0
  public void run() {

    Log.info(jobName, "启动[" + jobName + "]模块");
    do {
      Connection connection = null;

      try {
        connection = PoolHelper.getInstance().getConnection(com.wofu.ecommerce.ylw.Params.dbname);
        getRefund(connection);

      } catch (Exception e) {
        try {
          e.printStackTrace();
          if (connection != null && !connection.getAutoCommit()) connection.rollback();
        } catch (Exception e1) {
          Log.error(jobName, "回滚事务失败");
        }
        Log.error("105", jobName, Log.getErrorMessage(e));
      } finally {

        try {
          if (connection != null) connection.close();
        } catch (Exception e) {
          Log.error(jobName, "关闭数据库连接失败");
        }
      }
      System.gc();
      long startwaittime = System.currentTimeMillis();
      while (System.currentTimeMillis() - startwaittime
          < (long) (Params.waittime * 1000 * Params.timeInterval))
        try {
          sleep(1000L);
        } catch (Exception e) {
          Log.warn(jobName, "系统不支持休眠操作, 作业将严重影响机器性能");
        }
    } while (true);
  }
Example #11
0
  // 修改订单备注
  private void modifiRemark(Connection conn) throws Exception {
    String sql =
        "select sheetid,sender from it_upnote where sheettype=5 and flag=0 and receiver='"
            + Params.tradecontactid
            + "'";
    Vector modifiReList = SQLHelper.multiRowSelect(conn, sql);
    if (modifiReList.size() == 0) return;
    for (int i = 0; i < modifiReList.size(); i++) {
      try {
        Hashtable item = (Hashtable) modifiReList.get(i);
        String sheetid = item.get("sheetid").toString();
        String sender = item.get("sender").toString();
        String[] remarks = sender.split(":");
        // 订单号
        String tid = remarks[0];
        // 备注
        String remark = remarks[1];
        Map<String, String> params = new HashMap<String, String>();
        // 系统级参数设置
        params.put("appKey", Params.app_id);
        params.put("sessionKey", Params.token);
        params.put("format", Params.format);
        params.put("method", "yhd.order.merchant.remark.update");
        params.put("ver", Params.ver);
        params.put("timestamp", Formatter.format(new Date(), Formatter.DATE_TIME_FORMAT));
        params.put("orderCode", tid);
        params.put("remark", remark);

        String response = Utils.sendByPost(params, Params.AppSecret, Params.url);
        // Log.info("修改备注: "+response);

        JSONObject responseCount = new JSONObject(response);
        if (0 == (responseCount.getJSONObject("response").getInt("errorCount"))) {
          try {
            conn.setAutoCommit(false);
            sql =
                "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                    + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                    + " where SheetID = '"
                    + sheetid
                    + "' and SheetType = 5";
            SQLHelper.executeSQL(conn, sql);

            sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=5";

            SQLHelper.executeSQL(conn, sql);
            conn.commit();
            conn.setAutoCommit(true);
            Log.info(jobname, "处理订单【" + tid + "】 sheetid【" + sheetid + "】 修改备注成功");
          } catch (Exception ex) {
            if (!conn.getAutoCommit()) {
              try {
                conn.rollback();
              } catch (Exception el) {
              }
            }
            try {
              conn.setAutoCommit(true);
            } catch (Exception es) {
            }
            throw new Exception("事务回滚失败!");
          }
        } else {
          Log.info(jobname, "处理订单【" + tid + "】 sheetid【" + sheetid + "】 修改备注失败");
        }
      } catch (Exception ex) {
        Log.error(jobname, ex.getMessage());
      }
    }

    Log.info(jobname + ",修改订单备注完成");
  }
Example #12
0
  public void run() {
    Log.info(jobname, "启动[" + jobname + "]模块");

    do {
      Connection conn = null;
      try {
        conn = PoolHelper.getInstance().getConnection(Params.dbname);
        Holder ask = new Holder();
        Holder message = new Holder();
        Holder error = new Holder();
        HeaderRequest request = new HeaderRequest();
        request.setAppKey(Params.Key);
        request.setAppToken(Params.Token);
        request.setCustomerCode(Params.customercode);
        ServiceForProduct_Service service = new ServiceForProduct_Service();
        ServiceForProduct info = service.getServiceForProductSOAP();
        // 取得要处理的数据的单号  这个单号对应barcodetranlist的sheetid
        Vector infsheetlist = FedexUtil.getInfDownNote(conn, "9901");
        // 每一个单号发送一次请求
        for (Iterator it = infsheetlist.iterator(); it.hasNext(); ) {
          Hashtable ht = (Hashtable) it.next();
          String sheetid = ht.get("OperData").toString();
          Integer serialid = (Integer) ht.get("SerialID");
          Log.info("sheetid: " + sheetid);
          // skuCategory 产品分类   这个还没有表数据关联的
          String sql =
              " select CustomBC skuNo,g.Name skuName, g.Name skuEnName,rtrim(d.skuCategory) as skuCategory,g.customno,g.deptid, isnull(g.postTaxNo,'"
                  + "GDO51311409230000003') applyEnterpriseCode,u.uom UOM ,0 barcodeType,substring(Spec,1,128) "
                  + "specificationsAndModels,hsCode,g.Price productDeclaredValue,g.Name hsGoodsName,b.applyEnterpriseCodeCIQ,"
                  + "cc.code originCountry,br.name brand,case when isnull(Weigh,1000)/1000<1 then 1 else isnull(Weigh,1000)"
                  + "/1000 end as weight ,case when isnull(NetWeigh,1000)/1000<1 then 1 else isnull(NetWeigh,1000)/1000 end as netWeight"
                  + " from BarcodeTranList a , Barcode b , Merchandise g , PostTariff p,unit u,"
                  + "countrycode cc ,dept d ,brand br where a.BarcodeID = b.BarcodeID and b.MID = g.MID and g.unitname="
                  + "u.unitname and cc.name=g.origin and g.PostTaxNo = p.Code and d.deptid=g.deptid and g.brandid=br.BrandID and SheetID = '"
                  + sheetid
                  + "'";
          boolean isSuccess = false;
          Vector vtsku = SQLHelper.multiRowSelect(conn, sql);
          for (int i = 0; i < vtsku.size(); i++) {
            Hashtable htsku = (Hashtable) vtsku.get(i);
            ProductInfo productInfo = new ProductInfo();
            productInfo.getMapData(htsku);
            info.createProduct(request, productInfo, ask, message, error);
            if ("1".equals(ask.value)) {
              isSuccess = true;
              /*
              conn.setAutoCommit(false);
              FedexUtil.bakcUpDownNote(conn,serialid);
              conn.commit();
              conn.setAutoCommit(true);
              **/
              Log.info("添加商品成功,sku: " + productInfo.getSkuNo());
            } else {
              isSuccess = false;
              Log.info("上传商品数据失败: " + message.value);
              List<ErrorType> type = (List<ErrorType>) error.value;
              for (Iterator t = type.iterator(); t.hasNext(); ) {
                ErrorType err = (ErrorType) t.next();
                Log.info("上传商品数据失败: " + err.getErrorMessage());
              }
            }
          }
          if (isSuccess) { // 处理成功备份接口数据
            conn.setAutoCommit(false);
            FedexUtil.bakcUpDownNote(conn, serialid);
            conn.commit();
            conn.setAutoCommit(true);
          }
        }

      } catch (Exception e) {
        try {
          if (conn != null && !conn.getAutoCommit()) {
            conn.rollback();
            conn.setAutoCommit(true);
          }

        } catch (Exception e1) {
          Log.error(jobname, "回滚事务失败");
        }
        e.printStackTrace();
        Log.error("105", jobname, Log.getErrorMessage(e));
      } finally {
        try {
          if (conn != null) conn.close();
        } catch (Exception e) {
          Log.error(jobname, "关闭数据库连接失败");
        }
      }
      System.gc();
      long startwaittime = System.currentTimeMillis();
      while (System.currentTimeMillis() - startwaittime < (long) (Params.waittime * 1000))
        try {
          sleep(1000L);
        } catch (Exception e) {
          Log.warn(jobname, "系统不支持休眠操作, 作业将严重影响机器性能");
        }
    } while (true);
  }
Example #13
0
  public void getRefund(Connection conn) throws Exception {
    String resultText = "";
    for (int k = 0; k < 5; ) {
      try {
        // 获取到退货订单号
        String apiMethod = "suning.custom.batchrejectedOrd.query";
        HashMap<String, String> reqMap = new HashMap<String, String>();
        reqMap.put(
            "startTime",
            Formatter.format(
                new Date(System.currentTimeMillis() - daymillis), Formatter.DATE_TIME_FORMAT));
        reqMap.put("endTime", Formatter.format(new Date(), Formatter.DATE_TIME_FORMAT));
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("appSecret", Params.appsecret);
        map.put("appMethod", apiMethod);
        map.put("format", Params.format);
        map.put("versionNo", "v1.2");
        map.put("appKey", Params.appKey);
        // 发送请求
        String responseText = CommHelper.doRequest(map, Params.url);
        Log.info("退换货数据: " + responseText);
        // 把返回的数据转成json对象
        JSONObject responseObj = new JSONObject(responseText).getJSONObject("sn_responseContent");
        // 错误对象
        if (responseText.indexOf("sn_error") != -1) { // 发生错误
          String operCode = responseObj.getJSONObject("sn_error").getString("error_code");
          if (!"".equals(operCode)) {
            Log.error("苏宁获取退货订单", "获取退货订单失败,operCode:" + operCode);
          }
          return;
        }

        JSONArray ReturnCodeList =
            responseObj.getJSONObject("sn_body").getJSONArray("batchQueryRejectedOrd");
        for (int i = 0; i < ReturnCodeList.length(); i++) {
          try {
            String orderCode = ReturnCodeList.getJSONObject(i).getString("orderCode");
            Order o = new Order();
            OrderUtils.createRefundOrder(
                "生成苏宁退换货接口订单",
                conn,
                Params.tradecontactid,
                o,
                Params.url,
                Params.appKey,
                Params.appsecret,
                Params.format);
          } catch (Exception ex) {
            if (conn != null && !conn.getAutoCommit()) {
              conn.rollback();
            }
            Log.error(jobName, ex.getMessage());
            continue;
          }
        }

        break;

      } catch (Exception e) {
        if (++k >= 5) throw e;
        if (conn != null && !conn.getAutoCommit()) {
          conn.rollback();
        }
        Log.warn(jobName + " ,远程连接失败[" + k + "], 10秒后自动重试. " + Log.getErrorMessage(e));
        Thread.sleep(10000L);
      }
    }
  }
Example #14
0
  private void getInStockItems() throws Exception {

    int pageno = 1;

    Log.info("开始取一号店仓库商品资料");
    String sql =
        "select orgid from ecs_tradecontactorgcontrast with(nolock) where tradecontactid="
            + tradecontactid;
    int orgid = this.getDao().intSelect(sql);
    for (int k = 0; k < 10; ) {
      try {

        while (true) {
          Map<String, String> productparams = new HashMap<String, String>();
          // 系统级参数设置
          productparams.put("appKey", app_key);
          productparams.put("sessionKey", token);
          productparams.put("format", format);
          productparams.put("method", "yhd.serial.products.search");
          productparams.put("ver", ver);
          productparams.put("timestamp", Formatter.format(new Date(), Formatter.DATE_TIME_FORMAT));

          productparams.put("canShow", "1");
          productparams.put("canSale", "0");
          productparams.put("curPage", String.valueOf(pageno));
          productparams.put("pageRows", "20");
          productparams.put("verifyFlg", "2");

          String responseProductData = Utils.sendByPost(productparams, app_secret, url, "");
          Log.info("取仓库商品返回数据: " + responseProductData);

          JSONObject responseproduct = new JSONObject(responseProductData);

          int totalCount = responseproduct.getJSONObject("response").getInt("totalCount");

          JSONArray productlist =
              responseproduct
                  .getJSONObject("response")
                  .getJSONObject("serialProductList")
                  .getJSONArray("serialProduct");

          for (int i = 0; i < productlist.length(); i++) {
            JSONObject product = productlist.getJSONObject(i);

            long productId = product.optLong("productId");
            String productCode = product.optString("productCode");
            String productCname = product.optString("productCname");

            Log.info("货号:" + productCode + ",产品名称:" + productCname);

            StockManager.stockConfig(
                this.getDao(),
                orgid,
                Integer.valueOf(tradecontactid),
                String.valueOf(productId),
                productCode,
                productCname,
                0);

            Map<String, String> stockparams = new HashMap<String, String>();
            // 系统级参数设置
            stockparams.put("appKey", app_key);
            stockparams.put("sessionKey", token);
            stockparams.put("format", format);
            stockparams.put("method", "yhd.serial.product.get");
            stockparams.put("ver", ver);
            stockparams.put("timestamp", Formatter.format(new Date(), Formatter.DATE_TIME_FORMAT));

            stockparams.put("productId", String.valueOf(productId));

            String responseData = Utils.sendByPost(stockparams, app_secret, url, "");
            Log.info("取仓库商品详情返回数据: " + responseData);
            JSONObject responsestock = new JSONObject(responseData);

            JSONArray childseriallist =
                responsestock
                    .getJSONObject("response")
                    .getJSONObject("serialChildProdList")
                    .getJSONArray("serialChildProd");

            for (int m = 0; m < childseriallist.length(); m++) {
              JSONObject childserial = childseriallist.optJSONObject(m);

              String sku = childserial.optString("outerId");
              long skuid = childserial.optLong("productId");

              JSONArray stocklist =
                  childserial.getJSONObject("allWareHouseStocList").getJSONArray("pmStockInfo");

              for (int j = 0; j < stocklist.length(); j++) {
                JSONObject stock = stocklist.optJSONObject(j);

                int quantity = stock.optInt("vs");
                long warehouseId = stock.optLong("warehouseId");

                StockManager.addStockConfigSku(
                    this.getDao(),
                    Integer.valueOf(tradecontactid),
                    String.valueOf(productId),
                    String.valueOf(skuid) + "-" + String.valueOf(warehouseId),
                    sku,
                    quantity);
              }
            }
          }

          // 判断是否有下一页
          if (pageno == (Double.valueOf(Math.ceil(totalCount / 20.0))).intValue()) break;

          pageno++;
        }

        break;

      } catch (Exception e) {
        if (++k >= 10) throw e;
        Log.warn(jobName + ", 远程连接失败[" + k + "], 10秒后自动重试. " + Log.getErrorMessage(e));

        Thread.sleep(10000L);
      }
    }
  }
Example #15
0
  // 家装订单发货
  private void jzSend(
      String post_no, String orderid, String post_company, Connection conn, String sheetid) {
    try {

      TaobaoClient client = new DefaultTaobaoClient(Params.url, Params.appkey, Params.appsecret);
      WlbOrderJzwithinsConsignRequest req = new WlbOrderJzwithinsConsignRequest();
      req.setTid(TranTid(orderid));
      JSONObject obj = new JSONObject();
      obj.put("mail_no ", post_no);
      obj.put("zy_company ", post_company);
      req.setTmsPartner(obj.toString());
      JSONArray arr = new JSONArray(Params.jzParams);
      WlbOrderJzwithinsConsignResponse rsp;
      for (int i = 0; i < arr.length(); i++) {
        req.setInsPartner(arr.get(i).toString());
        rsp = client.execute(req, Params.authcode);
        String sql;
        if (rsp.isSuccess()) {

          try {
            conn.setAutoCommit(false);

            sql =
                "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                    + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                    + " where SheetID = '"
                    + sheetid
                    + "' and SheetType = 3";
            SQLHelper.executeSQL(conn, sql);

            sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

            SQLHelper.executeSQL(conn, sql);
            conn.commit();
            conn.setAutoCommit(true);
          } catch (SQLException sqle) {
            if (!conn.getAutoCommit())
              try {
                conn.rollback();
              } catch (Exception e1) {
              }
            try {
              conn.setAutoCommit(true);
            } catch (Exception e1) {
            }
            // throw new JSQLException(sql, sqle);
          }
          Log.info(
              username,
              "处理订单【" + orderid + "】发货成功,快递公司【" + post_company + "】,快递单号【" + post_no + "】",
              null);
          Log.info(username, "家装发货参数: " + arr.get(i).toString(), null);
          break;
        } else {
          Log.info(username, "家装订单发货失败,错误信息: " + rsp.getResultInfo(), null);
          continue;
        }
      }

    } catch (ApiException e) {

      Log.error(
          username,
          "处理订单【"
              + orderid
              + "】发货失败,快递公司【"
              + post_company
              + "】,快递单号【"
              + post_no
              + "】,错误信息:"
              + e.getMessage(),
          null);
    } catch (Exception e) {
      Log.error(username, "同步发货状态出错了, 错误信息: " + e.getMessage(), null);
    }
  }
Example #16
0
  private void synStock() throws Exception {
    // 店铺同步比例
    double synrate = 1;
    Log.info(username, "开始同步商品库存");

    StringBuffer updateItemsXML = new StringBuffer();

    String sql =
        "select orgid from ecs_tradecontactorgcontrast with(nolock) where tradecontactid="
            + tradecontactid;
    int orgid = this.getDao().intSelect(sql);

    sql = "update ecs_stockconfig set errflag=0,errmsg='' where orgid=" + orgid;
    this.getDao().execute(sql);

    sql = "update ecs_stockconfigsku set errflag=0,errmsg='' where orgid=" + orgid;
    this.getDao().execute(sql);
    // 店铺同步比例表
    sql = "select synrate from ecs_shopglobalconfig where shopOrgId=" + orgid;
    String temp = this.getDao().strSelect(sql);
    if (!"".equals(temp)) synrate = Float.parseFloat(temp);
    int n = 0;

    for (int k = 0; k < 10; ) {
      try {
        sql = "select * from ecs_stockconfig with(nolock) where orgid=" + orgid;
        Vector vtstockconfig = this.getDao().multiRowSelect(sql);
        for (int i = 0; i < vtstockconfig.size(); i++) {
          try {
            Hashtable htstockconfig = (Hashtable) vtstockconfig.get(i);

            ECS_StockConfig stockconfig = new ECS_StockConfig();
            stockconfig.getMapData(htstockconfig);

            String itemid = stockconfig.getItemid();
            Log.info("商品ID:" + stockconfig.getItemid() + " 货号:" + stockconfig.getItemcode());

            if (stockconfig.getIsneedsyn() == 0) {
              Log.info(username, "配置不需要同步库存,货号:" + stockconfig.getItemcode());
              continue; // 不需要同步
            }

            sql =
                "select * from ecs_stockconfigsku with(nolock) where orgid="
                    + orgid
                    + " and itemid='"
                    + stockconfig.getItemid()
                    + "'";

            Vector vtstockconfigsku = this.getDao().multiRowSelect(sql);

            for (int j = 0; j < vtstockconfigsku.size(); j++) {
              try {
                Hashtable htstockconfigsku = (Hashtable) vtstockconfigsku.get(j);

                ECS_StockConfigSku stockconfigsku = new ECS_StockConfigSku();
                stockconfigsku.getMapData(htstockconfigsku);

                Log.info(
                    username,
                    "SKU:" + stockconfigsku.getSku() + " 原库存:" + stockconfigsku.getStockcount());

                boolean ismulti = false;
                boolean isfind = true;

                sql =
                    "select count(*) from barcode with(nolock) where custombc='"
                        + stockconfigsku.getSku()
                        + "'";
                if (this.getDao().intSelect(sql) == 0) {
                  sql =
                      "select count(*) from MultiSKURef where refcustomercode='"
                          + stockconfigsku.getSku()
                          + "'";
                  if (this.getDao().intSelect(sql) == 0) {
                    Log.warn(
                        username,
                        "找不到SKU【"
                            + stockconfigsku.getSku()
                            + "】对应的条码,商品标题:"
                            + stockconfig.getTitle());

                    stockconfigsku.setErrflag(1);
                    stockconfigsku.setErrmsg("找不到SKU【" + stockconfigsku.getSku() + "】对应的条码");
                    this.getDao().updateByKeys(stockconfigsku, "orgid,itemid,skuid");

                    stockconfig.setErrflag(1);
                    stockconfig.setErrmsg("找不到SKU【" + stockconfigsku.getSku() + "】对应的条码");
                    this.getDao().updateByKeys(stockconfig, "orgid,itemid");

                    isfind = false;
                    continue;
                  } else ismulti = true;
                }

                int qty = 0;

                if (isfind) {
                  if (ismulti) {
                    int minqty = 1000000;
                    sql =
                        "select customercode,qty from MultiSKURef where refcustomercode='"
                            + stockconfigsku.getSku()
                            + "'";
                    Vector multiskulist = this.getDao().multiRowSelect(sql);
                    for (Iterator itmulti = multiskulist.iterator(); itmulti.hasNext(); ) {
                      Hashtable skuref = (Hashtable) itmulti.next();
                      String customercode = skuref.get("customercode").toString();
                      double skurefqty = Double.valueOf(skuref.get("qty").toString()).doubleValue();
                      qty =
                          StockManager.getTradeContactUseableStock(
                              this.getDao().getConnection(),
                              Integer.valueOf(tradecontactid).intValue(),
                              customercode);

                      qty = (Double.valueOf(Math.ceil(qty / skurefqty))).intValue();

                      if (qty < minqty) {
                        minqty = qty;
                      }
                    }

                    qty = minqty;
                  } else {
                    qty =
                        StockManager.getTradeContactUseableStock(
                            this.getDao().getConnection(),
                            Integer.valueOf(tradecontactid).intValue(),
                            stockconfigsku.getSku());
                  }

                  if (qty < 0) qty = 0;
                }

                int addstockqty = 0;
                if (Math.abs(stockconfig.getAddstockqty()) < 1)
                  addstockqty =
                      Double.valueOf(Math.floor(qty * stockconfig.getAddstockqty())).intValue();
                else addstockqty = Double.valueOf(stockconfig.getAddstockqty()).intValue();
                // 如果可用库存加上需增加的库存小于等于警戒库存,则将库存同步为0
                if ((qty + addstockqty) <= stockconfig.getAlarmqty()) {
                  qty = 0;
                } else {
                  qty = qty + addstockqty;
                }

                Log.info("old qty: " + qty);
                qty = Double.valueOf(Math.floor(qty * synrate)).intValue();
                Log.info("new qty: " + qty);
                // 更新库存开始
                StockUtils.UpdateSkuStock(
                    this.getDao(),
                    orgid,
                    url,
                    app_id,
                    secret,
                    session,
                    stockconfigsku.getSku(),
                    qty,
                    stockconfig,
                    stockconfigsku);

              } catch (Exception ex) {
                if (this.getConnection() != null && !this.getConnection().getAutoCommit())
                  this.getConnection().rollback();

                if (this.getExtconnection() != null && !this.getExtconnection().getAutoCommit())
                  this.getExtconnection().rollback();
                Log.error(jobName, ex.getMessage());
              }
            }

            k = 0;
          } catch (Exception ex) {
            if (this.getConnection() != null && !this.getConnection().getAutoCommit())
              this.getConnection().rollback();

            if (this.getExtconnection() != null && !this.getExtconnection().getAutoCommit())
              this.getExtconnection().rollback();
            Log.error(jobName, ex.getMessage());
          }
        }
        break;

      } catch (Exception e) {
        if (++k >= 10) throw e;
        if (this.getConnection() != null && !this.getConnection().getAutoCommit())
          this.getConnection().rollback();

        if (this.getExtconnection() != null && !this.getExtconnection().getAutoCommit())
          this.getExtconnection().rollback();
        Log.warn(jobName + ", 远程连接失败[" + k + "], 10秒后自动重试. " + Log.getErrorMessage(e));

        Thread.sleep(10000L);
      }
    }
  }
Example #17
0
  // 检查取消订单  4 取消
  private void checkCancleOrders() throws Exception {
    int pageIndex = 1;
    boolean hasNextPage = true;

    for (int k = 0; k < 10; ) {
      try {
        int n = 1;

        while (hasNextPage) {
          Date enddate = new Date();
          Date startdate = new Date(new Date().getTime() - daymillis);
          // 方法名
          String apimethod = "search_order_list";
          HashMap<String, Object> reqMap = new HashMap<String, Object>();
          reqMap.put("last_modify_st_time", startdate.getTime() / 1000L);
          reqMap.put("last_modify_en_time", enddate.getTime() / 1000L);
          reqMap.put("pages", String.valueOf(pageIndex));
          reqMap.put("counts", pageSize);
          reqMap.put("return_data", "json");
          reqMap.put("act", apimethod);
          reqMap.put("api_version", "1.0");

          Log.info("第" + pageIndex + "页");
          String responseText = CommHelper.doRequest(reqMap, url);
          Log.info("返回数据为: " + responseText);
          // 把返回的数据转成json对象
          JSONObject responseObj = new JSONObject(responseText);
          // sn_error
          if (!"success".equals(responseObj.getString("result"))) { // 发生错误
            String operCode = responseObj.getJSONObject("sn_error").getString("error_code");
            if ("biz.handler.data-get:no-result".equals(operCode)) { // 没有结果
              Log.info("没有可用的订单!");
            } else {
              Log.warn("取订单出错了,错误码: " + operCode);
            }

            break;
          }

          JSONObject orderInfos = responseObj.getJSONObject("info");
          // 总页数
          String orderTotal = String.valueOf(orderInfos.getString("counts"));
          int orderTotaltemp = Integer.parseInt(orderTotal);
          int pageTotalTemp =
              orderTotaltemp < Integer.parseInt(pageSize)
                  ? 1
                  : orderTotaltemp / Integer.parseInt(pageSize) == 0
                      ? Integer.parseInt(pageSize)
                      : orderTotaltemp / Integer.parseInt(pageSize) + 1;
          String pageTotal = String.valueOf(pageTotalTemp);
          Log.info("总订单数为: " + orderTotal);
          Log.info("总页数为: " + pageTotal);
          if (orderTotal == null || orderTotal.equals("") || orderTotal.equals("0")) {
            break;
          }
          // 订单元素
          JSONArray ordersList = orderInfos.getJSONArray("data_info");
          for (int i = 0; i < ordersList.length(); i++) { // 某个订单
            JSONObject orderInfo = ordersList.getJSONObject(i);
            int returnOrderCount = 0;
            // 订单编号
            String orderCode = (String) orderInfo.get("order_sn");
            if (orderInfo.isNull("shop_info")) continue;
            // 订单商品集合
            JSONArray items = orderInfo.getJSONArray("shop_info");
            // 构造一个订单对象
            Order o = new Order();
            o.setObjValue(o, orderInfo);
            o.setFieldValue(o, "shop_info", items);
            Log.info("发货状态: " + o.getShipping_status() + "付款状态: " + o.getPay_status());
            if (o != null) {
              if ("4".equals(o.getPay_status())) { // 正常订单
                Log.info("订单号: " + o.getOrder_sn());
                // 如果是等待发货订单,创建接口订单成功,减少其它店的库存

                try {
                  OrderUtils.createInterOrder(
                      this.getDao().getConnection(), o, tradecontactid, username);

                } catch (SQLException sqle) {
                  throw new JException("生成退货订单出错!" + sqle.getMessage());
                }
              }
            }
          }
          // 判断是否有下一页
          if ("".equals(pageTotal) || pageTotal == null) pageTotal = "0";
          if (pageIndex >= Integer.parseInt(pageTotal)) hasNextPage = false;
          else pageIndex++;

          n++;
        }
        break;
      } catch (Exception e) {
        e.printStackTrace();
        if (++k >= 10) throw e;
        if (this.getDao() != null && !this.getDao().getConnection().getAutoCommit()) {
          this.getDao().rollback();
        }
        Log.warn(jobName + " ,远程连接失败[" + k + "], 10秒后自动重试. " + Log.getErrorMessage(e));
        Thread.sleep(10000L);
      }
    }
    Log.info("本次取ecshop退货订单任务处理完毕!");
  }
Example #18
0
  /** 检查未入待发货订单 orderStatus=10 等待发货 这里检查一天时间的未入订单 */
  public void checkWaitStockOutOrders() throws Exception {
    Log.info(jobName + "任务开始!");
    Connection conn = this.getDao().getConnection();
    int pageIndex = 1;
    boolean hasNextPage = true;

    for (int k = 0; k < 5; ) {
      try {

        while (hasNextPage) {
          Date startdate = new Date(new Date().getTime() - daymillis);
          Date enddate = new Date();
          // 方法名
          String apimethod = "search_order_list";
          HashMap<String, Object> reqMap = new HashMap<String, Object>();
          reqMap.put("last_modify_st_time", startdate.getTime() / 1000L);
          reqMap.put("last_modify_en_time", enddate.getTime() / 1000L);
          reqMap.put("pages", String.valueOf(pageIndex));
          reqMap.put("counts", pageSize);
          reqMap.put("return_data", "json");
          reqMap.put("act", apimethod);
          reqMap.put("api_version", "1.0");
          // 发送请求

          Log.info("第" + pageIndex + "页");
          String responseText = CommHelper.doRequest(reqMap, url);
          Log.info("返回数据为: " + responseText);
          // 把返回的数据转成json对象
          JSONObject responseObj = new JSONObject(responseText.replaceAll(":null", ":\"\""));
          // 错误对象
          if (!"success".equals(responseObj.getString("result"))) { // 发生错误
            String operCode = responseObj.getJSONObject("sn_error").getString("error_code");
            if (operCode.indexOf("no-result") != -1) { // 没有数据直接退出方法体
              Log.error("获取ecshop订单列表", "获取订单列表失败,操作码:" + operCode);
              return;
            }
            hasNextPage = false;
            break;
          }

          JSONObject orderInfos = responseObj.getJSONObject("info");
          String orderTotal = String.valueOf(orderInfos.getString("counts"));
          int orderTotaltemp = Integer.parseInt(orderTotal);
          int pageTotalTemp =
              Double.valueOf(Math.ceil(orderTotaltemp / Double.parseDouble(Params.pageSize)))
                  .intValue();
          String pageTotal = String.valueOf(pageTotalTemp);

          Log.info("总订单数为: " + orderTotal);
          Log.info("总页数为: " + pageTotal);
          if (orderTotal == null || orderTotal.equals("") || orderTotal.equals("0")) {
            break;
          }
          // 订单元素
          JSONArray ordersList = orderInfos.getJSONArray("data_info");
          for (int i = 0; i < ordersList.length(); i++) { // 某个订单
            JSONObject orderInfo = ordersList.getJSONObject(i);
            // 订单编号
            String orderCode = (String) orderInfo.get("order_sn");
            if (orderInfo.isNull("shop_info")) continue;
            // 订单商品集合
            JSONArray items = orderInfo.getJSONArray("shop_info");
            // 构造一个订单对象
            Order o = new Order();
            o.setObjValue(o, orderInfo);
            o.setFieldValue(o, "shop_info", items);
            Log.info(
                "订单号: "
                    + o.getOrder_sn()
                    + ", 发货状态: "
                    + o.getShipping_status()
                    + "付款状态: "
                    + o.getPay_status());
            if (o != null) {
              if ("0".equals(o.getShipping_status()) && "2".equals(o.getPay_status())) { // 正常订单
                Log.info("检查到一条订单:" + orderCode);
                // 如果是等待发货订单,创建接口订单成功,减少其它店的库存
                if (!OrderManager.isCheck(jobName, conn, orderCode)) {
                  if (!OrderManager.TidLastModifyIntfExists(
                      jobName, conn, orderCode, new Date(o.getAdd_time() * 1000L))) {
                    try {
                      OrderUtils.createInterOrder(conn, o, tradecontactid, username);
                      for (Iterator ito = o.getShop_info().getRelationData().iterator();
                          ito.hasNext(); ) {
                        OrderItem item = (OrderItem) ito.next();
                        String sku = item.getProduct_sn();
                        StockManager.deleteWaitPayStock(
                            jobName, conn, tradecontactid, orderCode, sku);
                        long qty = (long) item.getGoods_number();
                        // 在ecs_rationconfig表中存在机构添加一条库存同步记录(不包括自己)
                        StockManager.addSynReduceStore(
                            jobName, conn, tradecontactid, "未发货", o.getOrder_sn(), sku, qty, false);
                      }

                    } catch (SQLException sqle) {
                      throw new JException("生成接口订单出错!" + sqle.getMessage());
                    }
                  }
                } // 订单状态 10待发货,20已发货,21部分发货,30交易成功 ,40交易关闭
              }
            }
          }
          // 判断是否有下一页
          if ("".equals(pageTotal) || pageTotal == null) pageTotal = "0";
          if (pageIndex >= Integer.parseInt(pageTotal)) hasNextPage = false;
          else pageIndex++;

          break;
        }
        Log.info(jobName + "执行完毕!");
        break;
      } catch (Exception e) {
        if (++k >= 5) throw e;
        if (conn != null && !conn.getAutoCommit()) {
          conn.rollback();
        }
        Log.warn(jobName + " ,远程连接失败[" + k + "], 10秒后自动重试. " + Log.getErrorMessage(e));
        Thread.sleep(10000L);
      }
    }
  }
Example #19
0
  /*
   * 获取一天之类的退款订单
   */
  private void getRefundBillList(Connection conn) throws Exception {
    long pageno = 1L;
    Date modified = Formatter.parseDate(lasttime, Formatter.DATE_TIME_FORMAT);
    for (int k = 0; k < 10; ) {
      try {
        TaobaoClient client =
            new DefaultTaobaoClient(Params.url, Params.appkey, Params.appsecret, "json");
        TmallEaiOrderRefundMgetRequest req = new TmallEaiOrderRefundMgetRequest();
        Date startdate =
            new Date(Formatter.parseDate(lasttime, Formatter.DATE_TIME_FORMAT).getTime() + 1000L);
        Date enddate =
            new Date(
                Formatter.parseDate(lasttime, Formatter.DATE_TIME_FORMAT).getTime() + daymillis);
        req.setStartTime(startdate);
        req.setEndTime(enddate);
        req.setPageNo(pageno);
        req.setPageSize(40L);
        req.setUseHasNext(true);
        TmallEaiOrderRefundMgetResponse response = client.execute(req, Params.authcode);

        while (true) {
          if (response.getRefundBillList() == null || response.getRefundBillList().size() <= 0) {
            if (pageno == 1) {
              try {
                // 如一天之内都取不到订单,而且当前天大于配置天,则将取订单最新时间更新为当前天的零点
                if (this.dateformat
                        .parse(Formatter.format(new Date(), Formatter.DATE_FORMAT))
                        .compareTo(
                            this.dateformat.parse(
                                Formatter.format(
                                    Formatter.parseDate(
                                        PublicUtils.getConfig(conn, lasttimeconfvalue, ""),
                                        Formatter.DATE_TIME_FORMAT),
                                    Formatter.DATE_FORMAT)))
                    > 0) {
                  try {
                    String value =
                        Formatter.format(
                                (new Date(
                                    Formatter.parseDate(
                                                PublicUtils.getConfig(conn, lasttimeconfvalue, ""),
                                                Formatter.DATE_TIME_FORMAT)
                                            .getTime()
                                        + daymillis)),
                                Formatter.DATE_FORMAT)
                            + " 00:00:00";
                    PublicUtils.setConfig(conn, lasttimeconfvalue, value);
                  } catch (JException je) {
                    Log.error(jobname, je.getMessage());
                  }
                }
              } catch (ParseException e) {
                Log.error(jobname, "不可用的日期格式!" + e.getMessage());
              }
            }
            break;
          }

          for (Iterator it = response.getRefundBillList().iterator(); it.hasNext(); ) {
            RefundBill refundbill = (RefundBill) it.next();

            Log.info(
                refundbill.getTid()
                    + " "
                    + refundbill.getStatus()
                    + " "
                    + refundbill.getModified());

            if (!RefundUtil.RefundBillisCheck(
                conn,
                String.valueOf(refundbill.getTid()),
                String.valueOf(refundbill.getRefundId()),
                refundbill.getModified())) {
              Trade td =
                  OrderUtils.getFullTrade(
                      String.valueOf(refundbill.getTid()),
                      Params.url,
                      Params.address,
                      Params.appsecret,
                      Params.authcode);

              RefundUtil.createRefundBill(conn, refundbill, td, Params.tradecontactid);
            }
            if (Formatter.parseDate(refundbill.getModified(), Formatter.DATE_TIME_FORMAT)
                    .compareTo(modified)
                > 0) {
              modified = Formatter.parseDate(refundbill.getModified(), Formatter.DATE_TIME_FORMAT);
            }
          }

          // 判断是否下一页
          if (response.getHasNext()) {
            pageno++;
          } else {
            break;
          }
        }
        if (modified.compareTo(Formatter.parseDate(lasttime, Formatter.DATE_TIME_FORMAT)) > 0) {
          try {
            String value = Formatter.format(modified, Formatter.DATE_TIME_FORMAT);
            PublicUtils.setConfig(conn, lasttimeconfvalue, value);
          } catch (JException je) {
            Log.error(jobname, je.getMessage());
          }
        }
        // 执行成功后不再循环
        break;
      } catch (Exception e) {
        if (++k >= 10) throw e;
        Log.warn("远程连接失败[" + k + "], 10秒后自动重试. " + Log.getErrorMessage(e));
        Thread.sleep(10000L);
      }
    }
  }
Example #20
0
  private void normalSend(
      String post_no, String orderid, String post_company, Connection conn, String sheetid) {
    try {

      TaobaoClient client = new DefaultTaobaoClient(Params.url, Params.appkey, Params.appsecret);
      LogisticsOfflineSendRequest req = new LogisticsOfflineSendRequest();
      req.setOutSid(post_no);
      req.setTid(TranTid(orderid));
      req.setCompanyCode(post_company);
      LogisticsOfflineSendResponse rsp = client.execute(req, Params.authcode);
      String sql;

      if (rsp.isSuccess()) {
        try {
          conn.setAutoCommit(false);

          sql =
              "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                  + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                  + " where SheetID = '"
                  + sheetid
                  + "' and SheetType = 3";
          SQLHelper.executeSQL(conn, sql);

          sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

          SQLHelper.executeSQL(conn, sql);
          conn.commit();
          conn.setAutoCommit(true);
        } catch (SQLException sqle) {
          if (!conn.getAutoCommit())
            try {
              conn.rollback();
            } catch (Exception e1) {
            }
          try {
            conn.setAutoCommit(true);
          } catch (Exception e1) {
          }
          // throw new JSQLException(sql, sqle);
        }
        Log.info(
            username,
            "处理订单【" + orderid + "】发货成功,快递公司【" + post_company + "】,快递单号【" + post_no + "】",
            null);
      } else {
        if (rsp.getSubCode().equals("isv.logistics-offline-service-error:B04")) {
          // 已经同步发货状态或退货成功了
          sql =
              "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                  + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                  + " where SheetID = '"
                  + sheetid
                  + "' and SheetType = 3";
          SQLHelper.executeSQL(conn, sql);

          sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

          SQLHelper.executeSQL(conn, sql);
          Log.info(username, "订单: " + orderid + ", sheetid: " + sheetid + ",状态异常,已备份到备份表", null);
        }
        if (rsp.getSubCode().equals("isv.logistics-offline-service-error:P38")) {
          // 已经同步发货状态或退货成功了
          sql =
              "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                  + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                  + " where SheetID = '"
                  + sheetid
                  + "' and SheetType = 3";
          SQLHelper.executeSQL(conn, sql);

          sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

          SQLHelper.executeSQL(conn, sql);
          Log.info(
              username,
              "订单: " + orderid + ", sheetid: " + sheetid + ",状态异常,,拆单校验未通过.已备份到备份表",
              null);
        }
        if (rsp.getSubCode().equals("isv.logistics-offline-service-error:S01")) {
          // 已经同步发货状态或退货成功了
          sql =
              "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                  + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                  + " where SheetID = '"
                  + sheetid
                  + "' and SheetType = 3";
          SQLHelper.executeSQL(conn, sql);

          sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

          SQLHelper.executeSQL(conn, sql);
          Log.info(username, "订单: " + orderid + ", sheetid: " + sheetid + ",状态异常,已备份到备份表", null);
        }
        if (rsp.getSubCode().indexOf("ORDER_NOT_FOUND_ERROR") != -1) {
          sql =
              "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                  + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                  + " where SheetID = '"
                  + sheetid
                  + "' and SheetType = 3";
          SQLHelper.executeSQL(conn, sql);

          sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

          SQLHelper.executeSQL(conn, sql);
          Log.error(username, jobName + ",订单号: " + orderid + ", 无法找到!", null);
        }
        if (rsp.getSubMsg().indexOf("不能重复发货") >= 0 || rsp.getSubMsg().indexOf("发货类型不匹配") >= 0) {
          sql =
              "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                  + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                  + " where SheetID = '"
                  + sheetid
                  + "' and SheetType = 3";
          SQLHelper.executeSQL(conn, sql);

          sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

          SQLHelper.executeSQL(conn, sql);
          Log.info(
              username,
              "订单【" + orderid + "】不能重复发货,快递公司【" + post_company + "】,快递单号【" + post_no + "】",
              null);
        } else if ((rsp.getSubMsg().indexOf("没有权限进行发货") >= 0)
            || rsp.getSubMsg().indexOf("没有权限发货") >= 0
            || rsp.getSubMsg().indexOf("当前订单状态不支持修改") >= 0) {
          sql =
              "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                  + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                  + " where SheetID = '"
                  + sheetid
                  + "' and SheetType = 3";
          SQLHelper.executeSQL(conn, sql);

          sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

          SQLHelper.executeSQL(conn, sql);
          Log.info(
              username,
              "没有权限发货,订单【" + orderid + "】,快递公司【" + post_company + "】,快递单号【" + post_no + "】",
              null);
        } else if (rsp.getSubMsg().indexOf("物流订单不存在") >= 0
            || rsp.getSubMsg().indexOf("订单已经被拆单") >= 0
            || rsp.getSubMsg().indexOf("当前操作的订单是拆单订单") >= 0) {
          TaobaoClient subclient =
              new DefaultTaobaoClient(Params.url, Params.appkey, Params.appsecret);
          LogisticsOfflineSendRequest subreq = new LogisticsOfflineSendRequest();
          subreq.setOutSid(post_no);
          subreq.setTid(TranTid(orderid));
          subreq.setCompanyCode(post_company);
          subreq.setIsSplit(1L);

          String subtids = "";

          sql =
              "select oid from customerorderitem a with(nolock),customerorder b with(nolock),"
                  + "customerdelive c with(nolock) where a.sheetid=b.sheetid and a.sheetid=c.refsheetid "
                  + "and c.customersheetid='"
                  + orderid
                  + "' and c.delivery='"
                  + post_company
                  + "' "
                  + "and c.deliverysheetid='"
                  + post_no
                  + "'";
          List sublist = SQLHelper.multiRowListSelect(conn, sql);
          for (Iterator it = sublist.iterator(); it.hasNext(); ) {
            String oid = (String) it.next();
            subtids = oid + "," + subtids;
          }
          subtids =
              (subtids != null && subtids != "" ? subtids.substring(0, subtids.length() - 1) : "");

          subreq.setSubTid(subtids);

          LogisticsOfflineSendResponse subrsp = client.execute(subreq, Params.authcode);

          if (subrsp.isSuccess()) {
            Log.info(
                jobName,
                "处理订单【"
                    + orderid
                    + "】,子订单【"
                    + subtids
                    + "】发货成功,快递公司【"
                    + post_company
                    + "】,快递单号【"
                    + post_no
                    + "】");
          }

          sql =
              "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                  + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                  + " where SheetID = '"
                  + sheetid
                  + "' and SheetType = 3";
          SQLHelper.executeSQL(conn, sql);

          sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

          SQLHelper.executeSQL(conn, sql);

          Log.info(
              username,
              "物流订单不存在或订单已经被拆单,订单【"
                  + orderid
                  + "】,快递公司【"
                  + post_company
                  + "】,快递单号【"
                  + post_no
                  + "】",
              null);
        } else if (rsp.getSubMsg().indexOf("运单号不符合规则或已经被使用") >= 0) {
          // 公司内部自提发货处理
          if ((post_no.toUpperCase().indexOf("1111111") >= 0)
              || (post_no.toUpperCase().indexOf("YJ") >= 0)) {
            sql =
                "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                    + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                    + " where SheetID = '"
                    + sheetid
                    + "' and SheetType = 3";
            SQLHelper.executeSQL(conn, sql);

            sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

            SQLHelper.executeSQL(conn, sql);

          } else {
            String cc = "";
            String memo = "";
            if (post_no.toUpperCase().indexOf("EH") == 0) {
              cc = "EMS";
            } else if (post_no.toUpperCase().indexOf("101") == 0) {
              cc = "SF";
            } else if (post_no.toUpperCase().indexOf("368") == 0) {
              cc = "STO";
            } else if (post_no.toUpperCase().indexOf("W") == 0) {
              cc = "YTO";
            } else {
              cc = post_company; // 把错误的运单号对应的订单号修改一下,让后面修改后的快递信息能正确写入sheettype=3
              orderid += "运单号不符合规则或已经被使用";
              memo += "运单号不符合规则或已经被使用";
            }

            sql =
                "update ns_delivery set companycode='"
                    + cc
                    + "',tid='"
                    + orderid
                    + "',memo='"
                    + memo
                    + "' where SheetID = '"
                    + sheetid
                    + "'";
            SQLHelper.executeSQL(conn, sql);
          }

          sql =
              "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                  + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                  + " where SheetID = '"
                  + sheetid
                  + "' and SheetType = 3";
          SQLHelper.executeSQL(conn, sql);

          sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

          SQLHelper.executeSQL(conn, sql);

          Log.info(
              jobName,
              "运单号不符合规则或已经被使用,订单【"
                  + orderid
                  + "】,快递公司【"
                  + post_company
                  + "】,快递单号【"
                  + post_no
                  + "】");
        } else {
          Log.info(
              username,
              "处理订单【"
                  + orderid
                  + "】发货失败,快递公司【"
                  + post_company
                  + "】,快递单号【"
                  + post_no
                  + "】"
                  + "错误信息:"
                  + rsp.getSubMsg()
                  + rsp.getMsg(),
              null);
          String errmsg = rsp.getSubMsg();
          Pattern par = Pattern.compile("This ban will last for (\\d{1,9}) more seconds");
          Matcher m = par.matcher(errmsg);
          if (m.find()) {
            long delayTime = Long.parseLong(m.group(1)) * 1000L;
            long now = System.currentTimeMillis();
            while (System.currentTimeMillis() < now + delayTime) {
              Thread.sleep(1000L);
            }
          }
        }
      }

    } catch (ApiException e) {

      Log.error(
          username,
          "处理订单【"
              + orderid
              + "】发货失败,快递公司【"
              + post_company
              + "】,快递单号【"
              + post_no
              + "】,错误信息:"
              + e.getMessage(),
          null);
    } catch (Exception e) {
      Log.error(username, "同步发货状态出错了, 错误信息: " + e.getMessage(), null);
    }
  }
  public void run() {
    Properties proper = StringUtil.getStringProperties(this.getExecuteobj().getParams());
    tid = proper.getProperty("tid");
    tradecontactid = proper.getProperty("tradecontactid");
    url = proper.getProperty("url");
    appkey = proper.getProperty("appkey");
    appsecret = proper.getProperty("appsecret");
    authcode = proper.getProperty("authcode");
    sellernick = proper.getProperty("sellernick");
    try {
      updateJobFlag(1);
      String sql = "select isnull(value,0) from config where name='等待付款订单是否进系统'";
      if ("1".equals(this.getDao().strSelect(sql))) ;
      waitbuyerpayisin = true;

      TaobaoClient client = new DefaultTaobaoClient(url, appkey, appsecret, "xml");
      TradeGetRequest req = new TradeGetRequest();
      req.setFields("tid,modified,status,orders.outer_sku_id,orders.num");
      req.setTid(Long.parseLong(tid));
      TradeGetResponse response = client.execute(req, authcode);

      if (response.getTrade() == null) {
        return;
      }

      Trade td = response.getTrade();

      if (td.getStatus().equals("WAIT_SELLER_SEND_GOODS")) {

        if (!OrderManager.isCheck(
            "检查淘宝订单", this.getDao().getConnection(), String.valueOf(td.getTid()))) {
          if (!OrderManager.TidLastModifyIntfExists(
              "检查淘宝订单",
              this.getDao().getConnection(),
              String.valueOf(td.getTid()),
              td.getModified())) {
            OrderUtils.createInterOrder(
                this.getDao().getConnection(), td, Params.tradecontactid, Params.username, true);
            for (Iterator ito = td.getOrders().iterator(); ito.hasNext(); ) {
              Order o = (Order) ito.next();
              String sku = o.getOuterSkuId();

              StockManager.deleteWaitPayStock(
                  jobName,
                  this.getDao().getConnection(),
                  Params.tradecontactid,
                  String.valueOf(td.getTid()),
                  sku);
              StockManager.addSynReduceStore(
                  jobName,
                  this.getDao().getConnection(),
                  Params.tradecontactid,
                  td.getStatus(),
                  String.valueOf(td.getTid()),
                  sku,
                  -o.getNum(),
                  false);
            }
          }
        }

        // 等待买家付款时记录锁定库存
      } else if (td.getStatus().equals("WAIT_BUYER_PAY")
          || td.getStatus().equals("TRADE_NO_CREATE_PAY")) {
        if (waitbuyerpayisin) {
          if (!OrderManager.TidLastModifyIntfExists(
              "检查淘宝订单",
              this.getDao().getConnection(),
              String.valueOf(td.getTid()),
              td.getModified())) {
            OrderUtils.createInterOrder(
                this.getDao().getConnection(), td, Params.tradecontactid, Params.username, false);
          }
        }
        for (Iterator ito = td.getOrders().iterator(); ito.hasNext(); ) {
          Order o = (Order) ito.next();
          String sku = o.getOuterSkuId();
          StockManager.addWaitPayStock(
              jobName,
              this.getDao().getConnection(),
              Params.tradecontactid,
              String.valueOf(td.getTid()),
              sku,
              o.getNum());
          StockManager.addSynReduceStore(
              jobName,
              this.getDao().getConnection(),
              Params.tradecontactid,
              td.getStatus(),
              String.valueOf(td.getTid()),
              sku,
              -o.getNum(),
              false);
        }

        // 付款以后用户退款成功,交易自动关闭
        // 释放库存,数量为负数
      } else if (td.getStatus().equals("TRADE_CLOSED")) {
        OrderManager.CancelOrderByCID(
            jobName, this.getDao().getConnection(), String.valueOf(td.getTid()));
        for (Iterator ito = td.getOrders().iterator(); ito.hasNext(); ) {
          Order o = (Order) ito.next();
          String sku = o.getOuterSkuId();
          StockManager.deleteWaitPayStock(
              jobName,
              this.getDao().getConnection(),
              Params.tradecontactid,
              String.valueOf(td.getTid()),
              sku);
          // StockManager.addSynReduceStore(jobName, this.getDao().getConnection(),
          // Params.tradecontactid, td.getStatus(),String.valueOf(td.getTid()),sku,
          // o.getNum(),false);
        }

        // 付款以前,卖家或买家主动关闭交易
        // 释放等待买家付款时锁定的库存
      } else if (td.getStatus().equals("TRADE_CLOSED_BY_TAOBAO")) {

        if (waitbuyerpayisin) {

          if (!OrderManager.TidLastModifyIntfExists(
              "检查淘宝订单",
              this.getDao().getConnection(),
              String.valueOf(td.getTid()),
              td.getModified())) {
            OrderUtils.createInterOrder(
                this.getDao().getConnection(), td, Params.tradecontactid, Params.username, false);
          }
        }

        for (Iterator ito = td.getOrders().iterator(); ito.hasNext(); ) {
          Order o = (Order) ito.next();
          String sku = o.getOuterSkuId();

          StockManager.deleteWaitPayStock(
              jobName,
              this.getDao().getConnection(),
              Params.tradecontactid,
              String.valueOf(td.getTid()),
              sku);

          if (StockManager.WaitPayStockExists(
              jobName,
              this.getDao().getConnection(),
              Params.tradecontactid,
              String.valueOf(td.getTid()),
              sku)) // 有获取到等待买家付款状态时才加库存
          {

            StockManager.addSynReduceStore(
                jobName,
                this.getDao().getConnection(),
                Params.tradecontactid,
                td.getStatus(),
                String.valueOf(td.getTid()),
                sku,
                o.getNum(),
                false);
          }
        }

      } else if (td.getStatus().equals("TRADE_FINISHED")) {

        for (Iterator ito = td.getOrders().iterator(); ito.hasNext(); ) {
          Order o = (Order) ito.next();
          String sku = o.getOuterSkuId();

          StockManager.deleteWaitPayStock(
              jobName,
              this.getDao().getConnection(),
              Params.tradecontactid,
              String.valueOf(td.getTid()),
              sku);

          // 更新结束时间

          OrderUtils.updateFinishedStatus(
              this.getDao().getConnection(), Params.tradecontactid, td.getTid(), td.getEndTime());
        }
      }

      // if(Params.isc)
      // {
      // 处理退货
      for (Iterator oit = td.getOrders().iterator(); oit.hasNext(); ) {
        Order o = (Order) oit.next();
        // Log.info("订单号:"+String.valueOf(td.getTid())+" 退货ID:"+String.valueOf(o.getRefundId()));
        if (o.getRefundId() > 0) {
          OrderUtils.getRefund(
              jobName,
              this.getDao().getConnection(),
              Params.url,
              Params.appkey,
              Params.appsecret,
              Params.authcode,
              Params.tradecontactid,
              td,
              o,
              String.valueOf(td.getTid()),
              o.getRefundId());
        }
      }

      updateJobFlag(0);
      Log.info(
          jobName,
          "执行作业成功 ["
              + this.getExecuteobj().getActivetimes()
              + "] ["
              + this.getExecuteobj().getNotes()
              + "] 下次处理时间: "
              + this.datetimeformat.format(this.getExecuteobj().getNextactive()));

    } catch (Exception e) {
      try {

        if (this.getDao().getConnection() != null
            && !this.getDao().getConnection().getAutoCommit()) {
          this.getDao().getConnection().rollback();
          this.getDao().getConnection().setAutoCommit(true);
        }

      } catch (Exception e1) {
        Log.error(jobName, "回滚事务失败");
        Log.error(jobName, e1.getMessage());
      }

      try {
        if (this.getExecuteobj().getSkip() == 1) {
          UpdateTimerJob();
        } else UpdateTimerJob(Log.getErrorMessage(e));
      } catch (Exception ex) {
        Log.error(jobName, "更新任务信息失败");
        Log.error(jobName, ex.getMessage());
      }
      Log.error(jobName, "错误信息:" + Log.getErrorMessage(e));

      Log.error(
          jobName,
          "执行作业失败 ["
              + this.getExecuteobj().getActivetimes()
              + "] ["
              + this.getExecuteobj().getNotes()
              + "] \r\n  "
              + Log.getErrorMessage(e));
    } finally {

      try {
        updateJobFlag(0);
      } catch (Exception e) {
        Log.error(jobName, e.getMessage());
        Log.error(jobName, "更新处理标志失败");
        TimerRunner.modifiedErrVect(this.getExecuteobj().getId());
      }

      try {
        if (this.getDao().getConnection() != null) {
          this.getDao().getConnection().setAutoCommit(true);
          this.getDao().getConnection().close();
        }

      } catch (Exception e) {
        Log.error(jobName, "关闭数据库连接失败");
      }
    }
  }
Example #22
0
  /*
   * 转入一个订单到接口表
   */
  public static void createInterOrder(
      Connection conn, String tradecontactid, String username, Order o)
      throws SQLException, JException {
    String sheetid = "";
    int haspostFee;
    String sql =
        "declare @Err int ; declare @NewSheetID char(16); execute  @Err = TL_GetNewSheetID 1105, @NewSheetID output;select @NewSheetID;";
    try {
      conn.setAutoCommit(false);
      sheetid = SQLHelper.strSelect(conn, sql);
      if (sheetid.trim().equals("")) throw new JSQLException(sql, "取接口单号出错!");

      // 加入到通知表
      sql =
          "insert into it_downnote(Owner , sheetid , sheettype , sender , receiver , notetime , handletime) values('yongjun','"
              + sheetid
              + "',1 , '"
              + tradecontactid
              + "' , 'yongjun' , getdate() , null) ";
      SQLHelper.executeSQL(conn, sql);

      if (Float.valueOf(o.getPostage()).compareTo(Float.valueOf("0.0")) > 0) haspostFee = 1;
      else haspostFee = 0;

      // 加入到单据表
      sql =
          "insert into ns_customerorder(CustomerOrderId,SheetID,Owner,tid,OrderSheetID,sellernick,"
              + " created ,payment,status,buyermemo,tradememo,paytime,totalfee,postfee,"
              + " buyernick,receivername,receiverstate,receivercity,receiverdistrict,"
              + " receiveraddress,receiverzip,receivermobile,receiverphone,buyeremail,haspostFee,"
              + " price,num,title,tradefrom,TradeContactID) "
              + " values("
              + "'"
              + sheetid
              + "','"
              + sheetid
              + "','yongjun','"
              + o.getOrderId()
              + "','','"
              + username
              + "',"
              + "'"
              + o.getCreatTime()
              + "','"
              + String.valueOf(
                  Float.valueOf(o.getMoney()) * Float.valueOf(o.getBuyNum())
                      + Float.valueOf(o.getPostage()))
              + "',"
              + "'"
              + o.getStatus()
              + "','"
              + o.getRemarks()
              + "','"
              + o.getRemarks()
              + "','"
              + o.getPaymentTime()
              + "','"
              + String.valueOf(Float.valueOf(o.getMoney()) * Float.valueOf(o.getBuyNum()))
              + "','"
              + o.getPostage()
              + "','"
              + o.getbuyerNick()
              + "'"
              + ",'"
              + o.getReceiverName()
              + "','"
              + o.getProvince()
              + "', '"
              + o.getCity()
              + "','','"
              + o.getAddress()
              + "', "
              + "'"
              + o.getZipCode()
              + "','"
              + o.getMobilePhone()
              + "','"
              + o.getMobilePhone()
              + "',"
              + "'"
              + o.getEmail()
              + "','"
              + String.valueOf(haspostFee)
              + "',"
              + "'"
              + o.getMoney()
              + "','"
              + o.getBuyNum()
              + "', '"
              + username
              + "','GROUPON','"
              + tradecontactid
              + "')";
      SQLHelper.executeSQL(conn, sql);

      sql =
          "insert into ns_orderitem(CustomerOrderId,orderItemId,SheetID,"
              + " sellernick,buyernick,created,outerskuid,totalfee,payment,"
              + " status,owner,num,price,skuid) values( "
              + "'"
              + sheetid
              + "','"
              + sheetid
              + "_"
              + o.getOrderId()
              + "','"
              + sheetid
              + "',"
              + "'"
              + username
              + "', '"
              + o.getbuyerNick()
              + "' ,'"
              + o.getCreatTime()
              + "', "
              + "'"
              + o.getSKU()
              + "' , '"
              + String.valueOf(Float.valueOf(o.getMoney()) * Float.valueOf(o.getBuyNum()))
              + "','"
              + String.valueOf(
                  Float.valueOf(o.getMoney()) * Float.valueOf(o.getBuyNum())
                      + Float.valueOf(o.getPostage()))
              + "' , "
              + "'"
              + o.getStatus()
              + "','yongjun',"
              + ""
              + o.getBuyNum()
              + ",'"
              + o.getMoney()
              + "','"
              + o.getSKU()
              + "')";
      SQLHelper.executeSQL(conn, sql);

      conn.commit();
      conn.setAutoCommit(true);
      Log.info("生成订单【" + o.getOrderId() + "】接口数据成功,接口单号【" + sheetid + "】");
    } catch (JSQLException e1) {
      if (!conn.getAutoCommit())
        try {
          conn.rollback();
        } catch (Exception e2) {
        }
      try {
        conn.setAutoCommit(true);
      } catch (Exception e3) {
      }
      throw new JException("生成订单【" + o.getOrderId() + "】接口数据失败!" + e1.getMessage());
    }
  }
Example #23
0
  /*
   * 获取某个项目一天之类的所有订单
   */
  public static void getBusinessOrderList(
      String modulename,
      Connection conn,
      Hashtable htwsinfo,
      String grouponid,
      Date starttime,
      Date endtime)
      throws JException {
    OMFactory soapFactory = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = soapFactory.createOMNamespace(htwsinfo.get("namespace").toString(), "");
    OMElement soapResponse = soapFactory.createOMElement("groupon", omNs);
    DisneyRequestBean requestBean = new DisneyRequestBean();
    String s = (new StringBuilder(String.valueOf(System.currentTimeMillis()))).toString();
    requestBean.setRequest_time(s);
    requestBean.setSign(
        MD5Util.MD5Encode(
            (new StringBuilder(grouponid))
                .append(s)
                .append(htwsinfo.get("key").toString())
                .toString()));
    requestBean.setGrouponid(grouponid);
    requestBean.setLimit(htwsinfo.get("limit").toString());
    requestBean.setTotal(htwsinfo.get("total").toString());

    requestBean.setStartTime(String.valueOf(starttime.getTime())); // 增加一秒
    requestBean.setEndTime(String.valueOf(endtime.getTime())); // 增加一天
    soapResponse.addChild(ObjBodyWriter.convertBeanToXml(requestBean, "request"));
    Options options = new Options();
    options.setTo(new EndpointReference(htwsinfo.get("wsurl").toString()));
    options.setAction("getBusinessProjectList");
    options.setProperty("__CHUNKED__", Boolean.valueOf(false));
    ServiceClient sender = null;
    try {
      sender = new ServiceClient();
      sender.setOptions(options);
      OMElement result = sender.sendReceive(soapResponse);

      Document doc = DOMHelper.newDocument(result.toString(), htwsinfo.get("encoding").toString());
      Element urlset = doc.getDocumentElement();
      NodeList orderinfonodes = urlset.getElementsByTagName("order_info");
      if (orderinfonodes.getLength() > 0) {
        for (int i = 0; i < orderinfonodes.getLength(); i++) {

          Element orderinfoelement = (Element) orderinfonodes.item(i);
          Order o = OrderUtils.getOrder(orderinfoelement);
          String orderid = o.getOrderId();
          String status = o.getStatus();
          String sku = o.getSKU();
          long qty = Long.valueOf(o.getBuyNum());
          Date updatetime = Formatter.parseDate(o.getPaymentTime(), Formatter.DATE_TIME_FORMAT);

          /*
           *1、如果状态为等待卖家发货则生成接口订单
           *2、删除等待买家付款时的锁定库存
           */
          Log.info(o.getOrderId() + " " + o.getStatus() + " " + o.getPaymentTime());
          if (status.equals("1")) {
            // 即使取订单时不需要判断订单是否存在,每天检查订单时需检查订单是否已经存在
            if (htwsinfo.get("style").toString().equals("0")) {
              try {
                createInterOrder(
                    conn,
                    htwsinfo.get("tradecontactid").toString(),
                    htwsinfo.get("username").toString(),
                    o);
                StockManager.deleteWaitPayStock(
                    modulename, conn, htwsinfo.get("tradecontactid").toString(), orderid, sku);
              } catch (SQLException sqle) {
                throw new JException("生成接口订单出错!" + sqle.getMessage());
              }
            } else {
              if (!OrderManager.TidExists("检查团宝未入订单", conn, String.valueOf(o.getOrderId()))) {
                if (OrderManager.TidIntfExists("检查团宝未入订单", conn, String.valueOf(o.getOrderId()))) {
                  Log.info(
                      "接口中存在,客户订单中不存在:"
                          + o.getOrderId()
                          + " "
                          + o.getStatus()
                          + " "
                          + o.getPaymentTime());
                } else {
                  Log.info(
                      "接口中不存在,客户订单中不存在:"
                          + o.getOrderId()
                          + " "
                          + o.getStatus()
                          + " "
                          + o.getPaymentTime());
                }
                try {
                  createInterOrder(
                      conn,
                      htwsinfo.get("tradecontactid").toString(),
                      htwsinfo.get("username").toString(),
                      o);
                  StockManager.deleteWaitPayStock(
                      modulename, conn, htwsinfo.get("tradecontactid").toString(), orderid, sku);
                } catch (SQLException sqle) {
                  throw new JException("生成接口订单出错!" + sqle.getMessage());
                }
              }
            }
          }
          // 等待买家付款时记录锁定库存
          else if (status.equals("0")) {
            StockManager.addWaitPayStock(
                modulename, conn, htwsinfo.get("tradecontactid").toString(), orderid, sku, qty);
            StockManager.addSynReduceStore(
                modulename,
                conn,
                htwsinfo.get("tradecontactid").toString(),
                status,
                orderid,
                sku,
                -qty,
                false);
            // 付款以后用户退款成功,交易自动关闭
            // 释放库存,数量为正数
          } else if (status.equals("6")) {
            StockManager.addSynReduceStore(
                modulename,
                conn,
                htwsinfo.get("tradecontactid").toString(),
                status,
                orderid,
                sku,
                qty,
                false);
            // 付款以前,卖家或买家主动关闭交易
            // 释放等待买家付款时锁定的库存
          } else if (status.equals("4")) {
            StockManager.deleteWaitPayStock(
                modulename, conn, htwsinfo.get("tradecontactid").toString(), orderid, sku);
            StockManager.addSynReduceStore(
                modulename,
                conn,
                htwsinfo.get("tradecontactid").toString(),
                status,
                orderid,
                sku,
                qty,
                false);
          }

          // 更新同步订单最新时间
          if (updatetime.compareTo(
                  Formatter.parseDate(
                      PublicUtils.getConfig(conn, htwsinfo.get("lasttimeconfvalue").toString(), ""),
                      Formatter.DATE_TIME_FORMAT))
              > 0)
            PublicUtils.setConfig(
                conn,
                htwsinfo.get("lasttimeconfvalue").toString(),
                Formatter.format(updatetime, Formatter.DATE_TIME_FORMAT));
        }
      } else {
        try {
          // 如该段时间之内都取不到订单,而且当前天大于配置天,则将取订单最新时间更新为当前天的零点
          if (dateformat
                  .parse(Formatter.format(new Date(), Formatter.DATE_FORMAT))
                  .compareTo(
                      dateformat.parse(
                          Formatter.format(
                              Formatter.parseDate(
                                  PublicUtils.getConfig(
                                      conn, htwsinfo.get("lasttimeconfvalue").toString(), ""),
                                  Formatter.DATE_TIME_FORMAT),
                              Formatter.DATE_FORMAT)))
              > 0) {

            PublicUtils.setConfig(
                conn,
                htwsinfo.get("lasttimeconfvalue").toString(),
                Formatter.format(
                        (new Date(
                            Formatter.parseDate(
                                        PublicUtils.getConfig(
                                            conn, htwsinfo.get("lasttimeconfvalue").toString(), ""),
                                        Formatter.DATE_TIME_FORMAT)
                                    .getTime()
                                + daymillis)),
                        Formatter.DATE_FORMAT)
                    + " 00:00:00");
          }
        } catch (ParseException e) {
          throw new JException("不可用的日期格式!" + e.getMessage());
        }
      }

    } catch (JException ja) {
      Log.error(modulename, ja.getMessage());
    } catch (AxisFault af) {
      throw new JException("访问远程服务出错!" + af.getMessage());
    } catch (Exception e) {
      throw new JException("解析XML出错!" + e.getMessage());
    }
  }
Example #24
0
  @Override
  public void run() {
    Properties prop = StringUtil.getStringProperties(this.getExecuteobj().getParams());
    pageSize = prop.getProperty("pageSize");
    url = prop.getProperty("url");
    tradecontactid = prop.getProperty("tradecontactid");
    username = prop.getProperty("username");

    try {
      // 检查未入订单
      updateJobFlag(1);
      checkWaitStockOutOrders();
      // 检查取消订单
      checkCancleOrders();

      UpdateTimerJob();

      Log.info(
          jobName,
          "执行作业成功 ["
              + this.getExecuteobj().getActivetimes()
              + "] ["
              + this.getExecuteobj().getNotes()
              + "] 下次处理时间: "
              + this.datetimeformat.format(this.getExecuteobj().getNextactive()));

    } catch (Exception e) {
      try {

        if (this.getExecuteobj().getSkip() == 1) {
          UpdateTimerJob();
        } else UpdateTimerJob(Log.getErrorMessage(e));

        updateJobFlag(0);

        if (this.getConnection() != null && !this.getConnection().getAutoCommit())
          this.getConnection().rollback();

        if (this.getExtconnection() != null && !this.getExtconnection().getAutoCommit())
          this.getExtconnection().rollback();

      } catch (Exception e1) {
        Log.error(jobName, "回滚事务失败");
      }
      Log.error(jobName, "错误信息:" + Log.getErrorMessage(e));

      Log.error(
          jobName,
          "执行作业失败 ["
              + this.getExecuteobj().getActivetimes()
              + "] ["
              + this.getExecuteobj().getNotes()
              + "] \r\n  "
              + Log.getErrorMessage(e));

    } finally {
      try {
        updateJobFlag(0);
      } catch (Exception e) {
        Log.error(jobName, "更新处理标志失败");
      }

      try {
        if (this.getConnection() != null) this.getConnection().close();
        if (this.getExtconnection() != null) this.getExtconnection().close();

      } catch (Exception e) {
        Log.error(jobName, "关闭数据库连接失败");
      }
    }
  }
Example #25
0
  private void delivery(Connection conn) throws Exception {

    String sql =
        "select  a.sheetid,b.tid, upper(ltrim(rtrim(b.companycode))) companycode,"
            + "upper(ltrim(rtrim(b.outsid))) outsid from it_upnote a with(nolock), ns_delivery b with(nolock)"
            + "where a.sheettype=3 and a.sheetid=b.sheetid and a.receiver='"
            + Params.tradecontactid
            + "' and b.iswait=0";
    Vector vdeliveryorder = SQLHelper.multiRowSelect(conn, sql);
    Log.info("本次要处理的订单发货条数为: " + vdeliveryorder.size());
    for (int i = 0; i < vdeliveryorder.size(); i++) {
      Hashtable hto = (Hashtable) vdeliveryorder.get(i);
      String sheetid = hto.get("sheetid").toString();
      String orderid = hto.get("tid").toString();
      String post_company = hto.get("companycode").toString();
      String post_no = hto.get("outsid").toString();

      // 如果物流公司为空则忽略处理
      if (post_company.trim().equals("")) {
        Log.warn(jobname, "快递公司为空!订单号:" + orderid + "");
        continue;
      }

      String postcompanyid = getCompanyID(post_company);

      if (postcompanyid.equals("")) {
        // 如果物流公司为空则忽略处理
        if (post_company.trim().equals("")) {
          Log.warn(jobname, "快递公司未配置!快递公司:" + post_company + " 订单号:" + orderid + "");
          continue;
        }
      }

      Map<String, String> params = new HashMap<String, String>();
      // 系统级参数设置
      params.put("app_id", Params.app_id);
      params.put("format", Params.format);
      params.put("method", "kdt.logistics.online.confirm");
      params.put("sign_method", "MD5");
      params.put("v", Params.ver);
      params.put("timestamp", Formatter.format(new Date(), Formatter.DATE_TIME_FORMAT));
      params.put("tid", orderid);
      params.put("is_no_express", "0");
      params.put("out_stype", postcompanyid);
      params.put("out_sid", post_no);

      String responseOrderListData = Utils.sendByPost(params, Params.AppSecret, Params.url);
      Log.info("result: " + responseOrderListData);
      // {"status":{"code":10006,"msg":"\u5fc5\u8981\u53c2\u6570\u7f3a\u5931"},"result":null}
      JSONObject responseDelivery = new JSONObject(responseOrderListData);

      if (!responseDelivery.isNull("error_response")) {
        String errdesc = responseDelivery.getJSONObject("error_response").getString("msg");
        if ("\u65e0\u6548\u7684\u8ba2\u5355\u53f7".equals(errdesc)) {
          Log.info(jobname + " 订单号不存在: " + orderid);

        } else {
          Log.warn(
              "订单发货失败,订单号:["
                  + orderid
                  + "],快递公司:["
                  + post_company
                  + "],快递单号:["
                  + post_no
                  + "] 错误信息:"
                  + errdesc);
          continue;
        }
      }

      try {
        conn.setAutoCommit(false);

        sql =
            "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                + " where SheetID = '"
                + sheetid
                + "' and SheetType = 3";
        SQLHelper.executeSQL(conn, sql);

        sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=3";

        SQLHelper.executeSQL(conn, sql);
        conn.commit();
        conn.setAutoCommit(true);
      } catch (SQLException sqle) {
        if (!conn.getAutoCommit())
          try {
            conn.rollback();
          } catch (Exception e1) {
          }
        try {
          conn.setAutoCommit(true);
        } catch (Exception e1) {
        }
        throw new JSQLException(sql, sqle);
      }
      Log.info(
          jobname, "处理订单【" + orderid + "】发货成功,快递公司【" + post_company + "】,快递单号【" + post_no + "】");
    }
  }
Example #26
0
  public void run() {
    Log.info(jobname, "启动[" + jobname + "]模块");

    do {
      Connection conn = null;
      try {
        conn = PoolHelper.getInstance().getConnection(Params.dbname);
        List infsheetlist = JwUtil.getintfsheetlist(conn, 900000, 100);
        Order order = null;
        for (Iterator it = infsheetlist.iterator(); it.hasNext(); ) {
          try {
            Hashtable ht = (Hashtable) it.next();
            Integer serialID = (Integer) ht.get("SerialID");
            String operData = (String) ht.get("OperData");
            String sql =
                "SELECT * from Inf_downNotebak where operdata='"
                    + operData
                    + "' AND SheetType='900000' AND result='success' and opertype='100'";
            Vector duplicateNum = SQLHelper.multiRowSelect(conn, sql);
            if (duplicateNum != null && duplicateNum.size() > 0) {
              conn.setAutoCommit(false);
              JwUtil.delBackUpIntsheetData(conn, serialID);
              conn.commit();
              conn.setAutoCommit(true);
              Log.info("此单已发送,删除重复的单成功,订单号: " + order.getOrderCode());
              continue;
            }
            sql =
                "select a.custompursheetid orderCode,a.custompursheetid orderDetailCode,a.tax "
                    + "orderTax,convert(varchar,a.notifydate,20) createDate,convert(varchar,a.notifydate,20) "
                    + "updateDate,convert(varchar,a.notifydate,20) payTime,a.postfee postPrice,a.CustomsOrderNo "
                    + "invoiceName,a.note buyerMessage,a.payfee amountReceivable,a.payfee actualPayment,"
                    + "a.linkman name, a.tele mobilePhone,a.address,isnull(a.zipcode,'000000') zip,b.notifyqty num,"
                    + "b.title,b.price,  b.price*b.notifyqty payment,b.price*b.notifyqty totalPrice,"
                    + "c.custombc skuID ,rtrim(c.outerSkuId) outerSkuId,a.customsbarcode hgBarcode "
                    + "from outstock0 a with(nolock),outstockitem0 b with(nolock),barcode c with(nolock) where a.sheetid=b.sheetid and b.barcodeid=c.barcodeid and a.sheetid='"
                    + operData
                    + "'";
            Vector sqlresult = SQLHelper.multiRowSelect(conn, sql);
            if (sqlresult.size() == 0) {
              conn.setAutoCommit(false);
              JwUtil.backUpIntsheetData(conn, serialID);
              conn.commit();
              conn.setAutoCommit(true);
              Log.info("同步订单失败,订单已经处理或不存在,订单号: " + order.getOrderCode());
              continue;
            }

            order = new Order();
            ReceiveInfo receiveInfo = new ReceiveInfo();
            int i = 0;
            detail det = null;
            for (Iterator t = sqlresult.iterator(); t.hasNext(); ) {
              Hashtable htTemp = (Hashtable) t.next();
              if (i == 0) {
                order.getMapData(htTemp);
                receiveInfo.getMapData(htTemp);
                String address = receiveInfo.getAddress();
                if (address.indexOf(" ") > 0) {
                  String[] add = address.split(" "); // 设置地址明细
                  if (add.length < 3) {
                    System.out.println(operData + " 地址不符合要求");
                  }
                  if (add.length == 4) {
                    receiveInfo.setProvince(add[0]);
                    receiveInfo.setCity(add[1]);
                    receiveInfo.setDistrict(add[2]);
                    receiveInfo.setAddress(add[3]);

                  } else if (add.length == 5) {
                    receiveInfo.setProvince(add[0]);
                    receiveInfo.setCity(add[1]);
                    receiveInfo.setDistrict(add[2]);
                    receiveInfo.setAddress(add[4].trim());
                  } else {
                    receiveInfo.setProvince(add[0]);
                    receiveInfo.setCity(add[1]);
                    receiveInfo.setDistrict(add[2]);
                  }
                }
                String mobilePhone = receiveInfo.getMobilePhone();
                mobilePhone = mobilePhone.replaceAll(" +", " ");
                if (mobilePhone.indexOf(" ") > 0) {
                  String[] contacts = mobilePhone.split(" ");
                  receiveInfo.setMobilephone(contacts[0]);
                  if (contacts[1].length() == 11) // 如果是手机号码就设置,如果是身份证就不设置了
                  receiveInfo.setPhone(contacts[1]);
                } else if (mobilePhone.indexOf("/") > 0) {
                  String[] contacts = mobilePhone.split("/");
                  if (contacts.length == 2) {
                    receiveInfo.setMobilephone(contacts[0]);
                    if (contacts[1].length() == 11) // 如果是手机号码就设置,如果是身份证就不设置了
                    receiveInfo.setPhone(contacts[1]);
                  }
                } else {
                  receiveInfo.setMobilephone(mobilePhone);
                }
              }
              det = new detail();
              det.getMapData(htTemp);
              order.getDetail().getRelationData().add(det);
              i++;
            }
            // Log.info("address: "+receiveInfo.getAddress());
            order.setReceiver(receiveInfo.toJSONObject());
            String temp = order.toJSONObject().replaceAll("\"\\{", "\\{");
            temp = temp.replaceAll("\",\"detail\"", ",\"detail\"");
            // Log.info("temp: "+temp);
            String bizData1 = "{\"saleOrderList\":[" + temp + "]}";
            String sign = JwUtil.makeSign(bizData1);
            Map requestParams =
                JwUtil.makeRequestParams(bizData1, service, Params.appkey, Params.format, sign);
            String result = CommHelper.sendRequest(Params.url, requestParams, "");
            Log.info("result: " + result);
            JSONObject re = new JSONObject(result);
            if (re.getBoolean("isSuccess")) {
              conn.setAutoCommit(false);
              JwUtil.backUpIntsheetData(conn, serialID);
              conn.commit();
              conn.setAutoCommit(true);
              Log.info("同步订单成功,订单号: " + order.getOrderCode());

            } else if (re.getString("body").contains("推送订单错误,可能已存在")) {
              conn.setAutoCommit(false);
              JwUtil.delBackUpIntsheetData(conn, serialID);
              conn.commit();
              conn.setAutoCommit(true);
              Log.info("删除重复的单成功,订单号: " + order.getOrderCode());
            } else {
              Log.error(jobname, "sheetid: " + operData + " " + re.getString("body"));
            }
          } catch (Exception e) {
            Log.error(jobname, e.getMessage());
            if (conn != null && !conn.getAutoCommit()) conn.rollback();
            continue;
          }
        }
      } catch (Exception e) {
        try {
          if (conn != null && !conn.getAutoCommit()) conn.rollback();
        } catch (Exception e1) {
          Log.error(jobname, "回滚事务失败");
        }
        Log.error("105", jobname, Log.getErrorMessage(e));
      } finally {
        try {
          if (conn != null) conn.close();
        } catch (Exception e) {
          Log.error(jobname, "关闭数据库连接失败");
        }
      }
      System.gc();
      long startwaittime = System.currentTimeMillis();
      while (System.currentTimeMillis() - startwaittime < (long) (Params.waittime * 1000))
        try {
          sleep(1000L);
        } catch (Exception e) {
          Log.warn(jobname, "系统不支持休眠操作, 作业将严重影响机器性能");
        }
    } while (true);
  }
Example #27
0
  public void run() {

    Properties prop = StringUtil.getStringProperties(this.getExecuteobj().getParams());

    url = prop.getProperty("url");
    tradecontactid = prop.getProperty("tradecontactid");
    username = prop.getProperty("username");
    app_id = prop.getProperty("app_id");
    secret = prop.getProperty("secret");
    session = prop.getProperty("session");
    System.out.println(url);
    System.out.println(tradecontactid);
    System.out.println(username);
    System.out.println(app_id);
    System.out.println(secret);
    System.out.println(session);
    try {

      updateJobFlag(1);

      synStock();

      UpdateTimerJob();

      Log.info(
          jobName,
          "执行作业成功 ["
              + this.getExecuteobj().getActivetimes()
              + "] ["
              + this.getExecuteobj().getNotes()
              + "] 下次处理时间: "
              + this.datetimeformat.format(this.getExecuteobj().getNextactive()));

    } catch (Exception e) {
      try {
        if (this.getExecuteobj().getSkip() == 1) {
          UpdateTimerJob();
        } else UpdateTimerJob(Log.getErrorMessage(e));

        if (this.getConnection() != null && !this.getConnection().getAutoCommit())
          this.getConnection().rollback();

        if (this.getExtconnection() != null && !this.getExtconnection().getAutoCommit())
          this.getExtconnection().rollback();

      } catch (Exception e1) {
        Log.error(jobName, "回滚事务失败");
      }
      Log.error(jobName, "错误信息:" + Log.getErrorMessage(e));

      Log.error(
          jobName,
          "执行作业失败 ["
              + this.getExecuteobj().getActivetimes()
              + "] ["
              + this.getExecuteobj().getNotes()
              + "] \r\n  "
              + Log.getErrorMessage(e));

    } finally {
      try {
        updateJobFlag(0);
      } catch (Exception e) {
        Log.error(jobName, "更新处理标志失败");
      }

      try {
        if (this.getConnection() != null) this.getConnection().close();
        if (this.getExtconnection() != null) this.getExtconnection().close();

      } catch (Exception e) {
        Log.error(jobName, "关闭数据库连接失败");
      }
    }
  }
Example #28
0
  /** 修改物流公司和运单号 已经发过货的订单才能进行此操作 api : taobao.logistics.consign.resend 免费 */
  private void resend(Connection conn) throws Exception {

    String sql =
        "select  a.sheetid,b.tid, upper(ltrim(rtrim(b.companycode))) companycode,"
            + " upper(ltrim(rtrim(b.outsid))) outsid from it_upnote a with(nolock), ns_delivery b with(nolock)"
            + "where a.sheettype=4 and a.sheetid=b.sheetid and a.receiver='"
            + Params.tradecontactid
            + "' and b.iswait=0";
    Vector vdeliveryorder = SQLHelper.multiRowSelect(conn, sql);
    for (int i = 0; i < vdeliveryorder.size(); i++) {
      String orderid = "";
      try {
        Hashtable hto = (Hashtable) vdeliveryorder.get(i);
        String sheetid = hto.get("sheetid") != null ? hto.get("sheetid").toString() : "";
        orderid = hto.get("tid") != null ? hto.get("tid").toString() : "";
        String post_company =
            hto.get("companycode") != null ? hto.get("companycode").toString().trim() : "";
        String post_no =
            hto.get("outsid").toString() != null ? hto.get("outsid").toString().trim() : "";

        // 如果物流公司为空则忽略处理
        if (post_company.trim().equals("")) {
          Log.warn(username, jobName + " 快递公司为空!订单号:" + orderid + "");
          continue;
        }

        // 如果物流公司为空则忽略处理
        if (post_no.trim().equals("")) {
          Log.warn(username, jobName + "快递单号为空!订单号:" + orderid + "");
          continue;
        }

        if (!StringUtil.isNumeric(orderid)) {
          sql =
              "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                  + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                  + " where SheetID = '"
                  + sheetid
                  + "' and SheetType = 4";
          SQLHelper.executeSQL(conn, sql);

          sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=4";

          SQLHelper.executeSQL(conn, sql);

          Log.warn(username, jobName + " 订单号【" + orderid + "】不全是数字!");
          continue;
        }

        TaobaoClient client = new DefaultTaobaoClient(Params.url, Params.appkey, Params.appsecret);
        LogisticsConsignResendRequest req = new LogisticsConsignResendRequest();
        req.setOutSid(post_no);
        req.setTid(TranTid(orderid));
        req.setCompanyCode(post_company);
        LogisticsConsignResendResponse rsp = client.execute(req, Params.authcode);

        if (rsp.isSuccess()) {

          try {
            conn.setAutoCommit(false);

            sql =
                "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                    + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                    + " where SheetID = '"
                    + sheetid
                    + "' and SheetType = 4";
            SQLHelper.executeSQL(conn, sql);

            sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=4";

            SQLHelper.executeSQL(conn, sql);
            conn.commit();
            conn.setAutoCommit(true);
          } catch (Exception sqle) {
            if (!conn.getAutoCommit())
              try {
                conn.rollback();
              } catch (Exception e1) {
              }
            try {
              conn.setAutoCommit(true);
            } catch (Exception e1) {
            }
            // throw new JSQLException(sql, sqle);
          }
          Log.info(
              username,
              "处理订单【" + orderid + "】发货成功,快递公司【" + post_company + "】,快递单号【" + post_no + "】",
              null);
        } else {

          if (rsp.getSubMsg().indexOf("不能重复发货") >= 0 || rsp.getSubMsg().indexOf("发货类型不匹配") >= 0) {
            sql =
                "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                    + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                    + " where SheetID = '"
                    + sheetid
                    + "' and SheetType = 4";
            SQLHelper.executeSQL(conn, sql);

            sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=4";

            SQLHelper.executeSQL(conn, sql);
            Log.info(
                username,
                "订单【" + orderid + "】不能重复发货,快递公司【" + post_company + "】,快递单号【" + post_no + "】",
                null);
          } else if (rsp.getSubMsg().indexOf("订单未发货") >= 0) {
            sql =
                "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                    + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                    + " where SheetID = '"
                    + sheetid
                    + "' and SheetType = 4";
            SQLHelper.executeSQL(conn, sql);

            sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=4";

            SQLHelper.executeSQL(conn, sql);
            Log.info(
                username,
                "订单【" + orderid + "】可能未发货,或已经退货,快递公司【" + post_company + "】,快递单号【" + post_no + "】",
                null);
          } else if ((rsp.getSubMsg().indexOf("没有权限进行发货") >= 0)
              || rsp.getSubMsg().indexOf("没有权限发货") >= 0
              || rsp.getSubMsg().indexOf("当前订单状态不支持修改") >= 0) {
            sql =
                "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                    + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                    + " where SheetID = '"
                    + sheetid
                    + "' and SheetType = 4";
            SQLHelper.executeSQL(conn, sql);

            sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=4";

            SQLHelper.executeSQL(conn, sql);
            Log.info(
                username,
                "没有权限发货,订单【" + orderid + "】,快递公司【" + post_company + "】,快递单号【" + post_no + "】",
                null);

          } else if (rsp.getSubMsg().indexOf("物流订单不存在") >= 0
              || rsp.getSubMsg().indexOf("订单已经被拆单") >= 0
              || rsp.getSubMsg().indexOf("当前操作的订单是拆单订单") >= 0) {
            TaobaoClient subclient =
                new DefaultTaobaoClient(Params.url, Params.appkey, Params.appsecret);
            LogisticsOfflineSendRequest subreq = new LogisticsOfflineSendRequest();
            subreq.setOutSid(post_no);
            subreq.setTid(TranTid(orderid));
            subreq.setCompanyCode(post_company);
            subreq.setIsSplit(1L);
            String subtids = "";

            sql =
                "select oid from customerorderitem a with(nolock),customerorder b with(nolock),"
                    + "customerdelive c with(nolock) where a.sheetid=b.sheetid and a.sheetid=c.refsheetid "
                    + "and c.customersheetid='"
                    + orderid
                    + "' and c.delivery='"
                    + post_company
                    + "' "
                    + "and c.deliverysheetid='"
                    + post_no
                    + "'";
            List sublist = SQLHelper.multiRowListSelect(conn, sql);
            if (sublist.size() > 0) {
              for (Iterator it = sublist.iterator(); it.hasNext(); ) {
                String oid = (String) it.next();
                subtids = oid + "," + subtids;
              }

              subtids = subtids.substring(0, subtids.length() - 1);

              subreq.setSubTid(subtids);

              LogisticsOfflineSendResponse subrsp = client.execute(subreq, Params.authcode);
              if (subrsp.isSuccess()) {
                Log.info(
                    username,
                    "处理订单【"
                        + orderid
                        + "】,子订单【"
                        + subtids
                        + "】发货成功,快递公司【"
                        + post_company
                        + "】,快递单号【"
                        + post_no
                        + "】",
                    null);
              }
            }

            sql =
                "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                    + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                    + " where SheetID = '"
                    + sheetid
                    + "' and SheetType = 4";
            SQLHelper.executeSQL(conn, sql);

            sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=4";

            SQLHelper.executeSQL(conn, sql);
            Log.info(
                jobName,
                "物流订单不存在或订单已经被拆,订单【"
                    + orderid
                    + "】,快递公司【"
                    + post_company
                    + "】,快递单号【"
                    + post_no
                    + "】");
          } else if (rsp.getSubMsg().indexOf("运单号不符合规则或已经被使用") >= 0) {
            // 公司内部自提发货处理
            if ((post_no.toUpperCase().indexOf("1111111") >= 0)
                || (post_no.toUpperCase().indexOf("YJ") >= 0)) {
              sql =
                  "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                      + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                      + " where SheetID = '"
                      + sheetid
                      + "' and SheetType = 4";
              SQLHelper.executeSQL(conn, sql);

              sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=4";

              SQLHelper.executeSQL(conn, sql);
            } else {
              String cc = "";
              if (post_no.toUpperCase().indexOf("EH") == 0) {
                cc = "EMS";
              } else if (post_no.toUpperCase().indexOf("101") == 0) {
                cc = "SF";
              } else if (post_no.toUpperCase().indexOf("368") == 0) {
                cc = "STO";
              } else if (post_no.toUpperCase().indexOf("W") == 0) {
                cc = "YTO";
              } else cc = post_company;

              sql =
                  "update ns_delivery set companycode='"
                      + cc
                      + "' where SheetID = '"
                      + sheetid
                      + "'";
              SQLHelper.executeSQL(conn, sql);
            }

            Log.info(
                username,
                "运单号不符合规则或已经被使用,订单【"
                    + orderid
                    + "】,快递公司【"
                    + post_company
                    + "】,快递单号【"
                    + post_no
                    + "】",
                null);
          } else if (rsp.getSubMsg().indexOf("该订单不支持修改") >= 0) {
            sql =
                "insert into IT_UpNoteBak(Owner,SheetID,SheetType,Sender,Receiver,Notetime,HandleTime,Flag) "
                    + " select Owner , SheetID , SheetType , Sender , Receiver , Notetime , getdate() , 1 from IT_UpNote "
                    + " where SheetID = '"
                    + sheetid
                    + "' and SheetType = 4";
            SQLHelper.executeSQL(conn, sql);

            sql = "delete from IT_UpNote where SheetID='" + sheetid + "' and sheettype=4";

            SQLHelper.executeSQL(conn, sql);
            Log.info(
                jobName,
                "处理订单【"
                    + orderid
                    + "】发货失败,快递公司【"
                    + post_company
                    + "】,快递单号【"
                    + post_no
                    + "】"
                    + "错误信息:"
                    + rsp.getSubMsg()
                    + rsp.getMsg());
          } else
            Log.info(
                username,
                "处理订单【"
                    + orderid
                    + "】发货失败,快递公司【"
                    + post_company
                    + "】,快递单号【"
                    + post_no
                    + "】"
                    + "错误信息:"
                    + rsp.getSubMsg()
                    + rsp.getMsg(),
                null);
        }
      } catch (Exception ex) {
        if (conn != null && !conn.getAutoCommit()) conn.rollback();
        Log.info(username, "修改发货信息作业出错,订单号: " + orderid + ",错误信息: " + ex.getMessage(), null);
      }
    }
  }