@RequestMapping(value = "/update")
 @AopLogModule(name = C.LOG_MODULE_PCRM, layer = C.LOG_LAYER_CONTROLLER)
 public @ResponseBody String saveOrUpdateSession(
     HttpServletRequest request, String appkey, String seller, String session) {
   String result = "false";
   System.out.println(appkey + ":" + seller + session);
   seller = seller.replace("cntaobao", "").split(":")[0];
   try {
     UserGetResponse resp = topService.getUserInfo(seller);
     if (resp.isSuccess()) {
       Long userid = resp.getUser().getUserId();
       result = String.valueOf(lkp.saveOrUpdateSession(userid, seller, appkey, session));
     } else System.out.println("error:" + resp.getSubMsg());
   } catch (ApiException e) {
     e.printStackTrace();
   }
   // request.setAttribute("result", result);
   return "result:" + result;
 }
Exemple #2
0
 public static void sms() {
   String url = "https://eco.taobao.com/router/rest";
   String appkey = "23377240";
   String secret = "ec63296b5e2886ed8d2fa7079fc8b583";
   String start = new Date().toString();
   TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
   AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
   //		req.setExtend( "extend" );
   req.setSmsType("normal");
   req.setSmsFreeSignName("方方测试");
   req.setSmsParamString(
       "{\"pwd\":\"1234\",\"startTime\":\"2016-06-01 \" ,\"endTime\":\"2016-07-01 \",\"msg\":\"退房时请保持室内清洁,谢谢 \"}");
   req.setRecNum("18910415779");
   req.setSmsTemplateCode("SMS_10200803");
   AlibabaAliqinFcSmsNumSendResponse rsp;
   try {
     rsp = client.execute(req);
     log.info(start + ">>fangfangtest>>    " + rsp.getBody());
   } catch (ApiException e) {
     e.printStackTrace();
   }
 }
  @Override
  @GET
  @Path("/produceOrder/mock/{topic}/{orderid}/{lineid}/{refundFee}")
  public Response mockProcess(
      @PathParam("orderid") final String orderid,
      @PathParam("topic") final String topic,
      @PathParam("lineid") final String lineid,
      @PathParam("refundFee") final String refundFee) {
    LOG.info(
        "Tmall JSC --- Mock Event Topic["
            + topic
            + "] OrderId["
            + orderid
            + "] LineId["
            + lineid
            + "] RefundFee["
            + refundFee
            + "]");
    final TradeFullinfoGetRequest req = new TradeFullinfoGetRequest();
    req.setFields(
        "payment,created,tid,status,buyer_nick,receiver_name,receiver_address,receiver_mobile,receiver_phone,discount_fee,post_fee,has_yfx,yfx_fee,has_post_fee,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,real_point_fee,received_payment,pay_time,orders");
    req.setTid(Long.parseLong(orderid));
    TradeFullinfoGetResponse response = null;
    try {
      response = taobaoclient.execute(req, defaultTmallStoreSessionkey);
      final Trade trade = response.getTrade();
      final Message message = new Message();
      final Map<String, Object> rawMap = new HashMap<String, Object>();
      final Map<String, Object> contentMap = new HashMap<String, Object>();
      contentMap.put("tid", trade.getTid());
      contentMap.put(
          "oid", "*".equals(lineid) ? String.valueOf(trade.getOrders().get(0).getOid()) : lineid);
      contentMap.put("type", trade.getType());
      contentMap.put("payment", trade.getPayment());
      contentMap.put("buyer_nick", trade.getBuyerNick());
      if ("*".equals(refundFee) == false) {
        contentMap.put("refund_fee", refundFee);
      }

      final String contentMapJson = new JSONSerializer().deepSerialize(contentMap);
      rawMap.put("content", contentMapJson);
      rawMap.put("time", String.valueOf(new Date()));
      setRawMsg(message, rawMap);

      LOG.info("---Tmall JSC---> " + message.getRaw());
      message.setUserId(911757567L);
      message.setTopic(topic);

      final OrderCommand command =
          OrderCommandFactory.createTmallOrderCommand(
              omsOrderRetrieverService, message, InnerSource.JSC);
      if (command != null) {
        OrderCommandsStorage.getInstance()
            .addOrderCommand(command.getChannelSource(), command.getEventType(), command);
      }

    } catch (final ApiException e) {
      LOG.error(e.getMessage(), e);
      throw new RuntimeException(e);
    }

    return Response.ok("OK").build();
  }
  public void syncTrades(Visitor visitor) {
    if (visitor == null) {
      return;
    }
    long pageSize = 50;
    String sessionKey = visitor.getSessionKey();
    if (StringUtils.isEmpty(sessionKey)) {
      return;
    }

    Date createdStart = getQueryStartDate(visitor);

    logger.debug(
        String.format(
            "About to synchronize trades for %s since %s",
            visitor.getVisitorNick(), createdStart.toString()));

    DefaultTaobaoClient client =
        new DefaultTaobaoClient(
            wiyReportConfiguration.getRestfulApi(),
            wiyReportConfiguration.getAppKey(),
            wiyReportConfiguration.getAppSecret(),
            Constants.FORMAT_JSON,
            30000,
            300000);

    TradesSoldGetRequest req = new TradesSoldGetRequest();
    req.setUseHasNext(true);
    req.setStartCreated(createdStart);
    req.setPageSize(pageSize);
    req.setFields(
        "seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type");
    try {
      long pageNumber = 1;
      while (true) {
        req.setPageNo(pageNumber);

        TradesSoldGetResponse response = client.execute(req, sessionKey);
        List<Trade> trades = response.getTrades();

        if (trades != null) {
          Hashtable<Long, TradeEntity> existed = getLongTradeEntityHashtable(trades);

          for (Trade trade : trades) {
            TradeEntity entity = EntityBuilder.buildTradeEntity(trade, visitor.getVisitorId());

            if (existed.containsKey(trade.getTid())) {
              TradeEntity existedTradeEntity = existed.get(trade.getTid());
              EntityBuilder.updateTradeEntity(existedTradeEntity, entity);
              entity = existedTradeEntity;
            }

            tradeEntityRepository.save(entity);
          }
        }

        if (response.getHasNext() == null || !response.getHasNext()) {
          break;
        }
        ++pageNumber;
      }
    } catch (ApiException e) {
      logger.error(e.getMessage(), e);
    } finally {
      // rebuild consumer entities
      daoService.buildConsumersBy(visitor.getVisitorId());
      // rebuild product purchase
      Date today = Calendar.getInstance().getTime();
      Date yesterday = DateTimeUtils.dateAdjust(today, Calendar.DAY_OF_YEAR, -1);
      daoService.buildProductPurchaseForSeller(visitor.getVisitorId(), yesterday, today);
      // rebuild produce entities
      daoService.buildProductEntitiesForSeller(visitor.getVisitorId(), yesterday, today);
      // build product purchase combo measurements
      daoService.buildProductPurchaseComboMeasurements();

      logger.debug(CommonService.class.getCanonicalName() + " finished.");
    }
  }
  // 家装订单发货
  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);
    }
  }
  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);
    }
  }