示例#1
0
 /**
  * 获取交易订单(普通数据,用于大批量活动导入)
  *
  * @param status
  * @param start
  * @param end
  * @return
  * @throws ApiException
  */
 public List<Long> getTids(String status, Date start, Date end) throws ApiException {
   TradesSoldIncrementGetRequest req = new TradesSoldIncrementGetRequest();
   req.setFields("tid");
   req.setType(TRADE_TYPE);
   if (StringUtils.isNotBlank(status)) {
     req.setStatus(status);
   }
   req.setStartModified(start);
   req.setEndModified(end);
   req.setPageSize(100L);
   req.setUseHasNext(false);
   TradesSoldIncrementGetResponse rsp = client.execute(req, sessionKey());
   List<Long> tids = new ArrayList<Long>();
   if (rsp.isSuccess()) {
     long pageCount = (rsp.getTotalResults() + req.getPageSize() - 1) / req.getPageSize();
     while (pageCount > 0) {
       req.setPageNo(pageCount);
       req.setUseHasNext(true); // 终止统计
       rsp = client.execute(req, sessionKey());
       if (rsp.isSuccess()) {
         for (Trade trade : rsp.getTrades()) {
           tids.add(trade.getTid());
         }
         pageCount--;
       }
     }
   }
   return tids;
 }
示例#2
0
 private Hashtable<Long, TradeEntity> getLongTradeEntityHashtable(List<Trade> trades) {
   Hashtable<Long, TradeEntity> existed = new Hashtable<Long, TradeEntity>();
   List<Long> tids = new ArrayList<Long>();
   for (Trade trade : trades) {
     tids.add(trade.getTid());
   }
   Collection entities = tradeEntityRepository.findTradeEntitiesByTids(tids);
   for (Object o : entities) {
     TradeEntity e = (TradeEntity) o;
     existed.put(e.getTid(), e);
   }
   return existed;
 }
  @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();
  }
示例#4
0
  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.");
    }
  }
  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, "关闭数据库连接失败");
      }
    }
  }