InsertServiceImpl.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package com.uas.eis.serviceImpl;
  2. import com.taobao.api.DefaultTaobaoClient;
  3. import com.taobao.api.TaobaoClient;
  4. import com.taobao.api.domain.Order;
  5. import com.taobao.api.domain.Trade;
  6. import com.uas.eis.dao.BaseDao;
  7. import com.uas.eis.service.InsertService;
  8. import net.sf.json.JSON;
  9. import net.sf.json.JSONArray;
  10. import net.sf.json.JSONObject;
  11. import oracle.sql.DATE;
  12. import org.apache.commons.lang.StringUtils;
  13. import org.apache.log4j.Logger;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.scheduling.annotation.Scheduled;
  16. import org.springframework.stereotype.Service;
  17. import java.text.SimpleDateFormat;
  18. import com.uas.eis.utils.DateUtil;
  19. import java.util.*;
  20. import com.taobao.api.request.TradesSoldGetRequest;
  21. import com.taobao.api.response.TradesSoldGetResponse;
  22. import com.taobao.api.request.TradesSoldIncrementGetRequest;
  23. import com.taobao.api.response.TradesSoldIncrementGetResponse;
  24. import com.taobao.api.request.TopOaidDecryptRequest;
  25. import com.taobao.api.response.TopOaidDecryptResponse;
  26. import com.uas.eis.utils.HttpUtil;
  27. import com.uas.eis.utils.HttpUtil.Response;
  28. @Service
  29. public class InsertServiceImpl implements InsertService {
  30. // TOP服务地址,正式环境需要设置为http://gw.api.taobao.com/router/rest
  31. public static final String serverUrl = "gw.api.taobao.com/router/rest";
  32. // private static final String serverUrl = "http://gw.api.tbsandbox.com/router/rest";
  33. public static final String appKey = "31921866"; // 可替换为您的沙箱环境应用的appKey /* 待修改 */
  34. public static final String appSecret = "7121c52d4c9970ba08bf09e2f525acd0"; // 可替换为您的沙箱环境应用的appSecret /* 待修改 */
  35. // public static final String sessionKey = "61024291979328cd09f0ba138f79236d66bd313f3364cf148715824"; // 必须替换为沙箱账号授权得到的真实有效sessionKey /* 待修改 */
  36. public static Logger logger = Logger.getLogger(InsertServiceImpl.class);
  37. @Autowired
  38. private BaseDao baseDao;
  39. @Override
  40. public String Insert(String code, String param) {
  41. try {
  42. Timer timer = new Timer();//实例化Timer类
  43. timer.schedule(new TimerTask() {
  44. public void run() {
  45. getAllDate();
  46. }
  47. }, 600000);//10分钟
  48. } catch (Exception e) {
  49. logger.info(this.getClass() + "服务挂掉");
  50. return e.getMessage();
  51. }
  52. return null;
  53. }
  54. public String trimNull(String str){
  55. if("".equals(str)||str==null||"null".equals(str)){
  56. return "";
  57. }else{
  58. return str.trim();
  59. }
  60. }
  61. @Autowired
  62. @Scheduled(cron = "0 0/8 * * * ?")
  63. public void getAllDate() {
  64. // 1.无淘宝自动抓取的 订单 ,则正常备份历史订单
  65. // 有淘宝自动抓取的 订单 ,则调用增量备份
  66. List<Trade> trades = new ArrayList<Trade>();
  67. String sa_remark = baseDao.queryForObject("select distinct sa_remark from sale where sa_remark ='淘宝对接接口抓所有' ", String.class);
  68. //String session_Key = baseDao.queryForObject(" select tb_code from ( select row_number() over(partition by TB_OPENUID order by tb_date desc ) xuhao , tb_code from tbauthorization ) where xuhao=1 ", String.class);
  69. List<Map<String,Object>> list = baseDao.queryForList(" select tb_code from ( select row_number() over(partition by TB_OPENUID order by tb_date desc ) xuhao , tb_code from tbauthorization ) where xuhao=1");
  70. for (int z = 0; z < list.size(); z++) {
  71. String session_Key = list.get(z).get("tb_code").toString();
  72. if (sa_remark == null || sa_remark == "") {
  73. TaobaoClient client = new DefaultTaobaoClient("http://39.98.201.114:30001/router/rest", "31921866", "7121c52d4c9970ba08bf09e2f525acd0");
  74. TradesSoldGetRequest req = new TradesSoldGetRequest(); //正常备份接口
  75. req.setFields("total_results,has_next,trades,seller_nick,pic_path,payment,seller_rate,post_fee,receiver_name,receiver_state,receiver_address,receiver_zip,receiver_mobile"+
  76. ",receiver_phone,consign_time,received_payment,receiver_country,receiver_town,order_tax_fee,shop_pick,tid,num,num_iid,status,title,type,price,discount_fee"+
  77. ",total_fee,created,pay_time,modified,end_time,seller_flag,buyer_nick,has_buyer_message,credit_card_fee,step_trade_status,step_paid_fee,mark_desc,shipping_type"+
  78. ",adjust_fee,trade_from"+
  79. ",service_orders,oid,item_oid,service_id,service_detail_url,num,price,payment,title,total_fee,buyer_nick,refund_id,seller_nick,pic_path"+
  80. ",tmser_spu_code,oid_str,buyer_rate,receiver_city,receiver_district,o2o,o2o_guide_id,o2o_delivery,"+
  81. ",orders,item_meal_name,pic_path,seller_nick,buyer_nick,refund_status,outer_iid,snapshot_url,snapshot,timeout_action_time,buyer_rate,seller_rate"+
  82. ",seller_type,cid,sub_order_tax_fee,sub_order_tax_rate,oid,status,title,item_oid,type,sku_properties_name,order_attr,shipping_type"+
  83. ",md_qualification,customization,inv_type,shipper,f_type,f_status,f_term,assembly_rela,cl_down_payment,cl_month_payment,cl_tail_payment"+
  84. ",cl_installment_num,cal_penalty,cl_service_fee,cl_car_taker,cl_car_taker_phone,cl_car_taker_i_d_num,cl_car_taker_id_num,down_payment"+
  85. ",down_payment_ratio,month_payment,tail_payment,installment_num,penalty,service_fee,oid_str,nr_reduce_inv_fail,sort_info"+
  86. ",rt_omni_outer_sc_id,rt_omni_sc_id,modify_address,ti_modify_address_time,omni_jxs_outerid,propoint,brand_light_shop_source,special_refund_type"+
  87. ",extend_info,service_type,threepl_timing,is_o2o_passport,delivery_time,sign_time");
  88. Calendar calendar3 = Calendar.getInstance();
  89. calendar3.setTime(new Date());
  90. calendar3.set(Calendar.HOUR_OF_DAY, 0);
  91. calendar3.set(Calendar.MINUTE, 0);
  92. calendar3.set(Calendar.SECOND, 0);
  93. calendar3.add(calendar3.DATE,-2);
  94. Date zero3 = calendar3.getTime();
  95. // req.setStartCreated(StringUtils.parseDateTime("2020-01-05 00:00:00"));
  96. Date date = new Date();
  97. Calendar calendar = Calendar.getInstance();
  98. calendar.setTime(new Date());
  99. calendar.set(Calendar.HOUR_OF_DAY, 23);
  100. calendar.set(Calendar.MINUTE, 59);
  101. calendar.set(Calendar.SECOND, 59);
  102. Date endtime = calendar.getTime();
  103. req.setStartCreated(zero3);
  104. req.setEndCreated(endtime);
  105. try {
  106. TradesSoldGetResponse rsp = client.execute(req, session_Key);
  107. trades = rsp.getTrades();
  108. } catch (Exception e) {
  109. //logger.info( new SimpleDateFormat("YYYY-MM-DD hh24:mi:ss").format(new Date())+ this.getClass() + "淘宝未响应并返回订单数据");
  110. logger.info("淘宝未响应并返回订单数据");
  111. }
  112. } else {
  113. TaobaoClient client2 = new DefaultTaobaoClient("http://39.98.201.114:30001/router/rest", "31921866", "7121c52d4c9970ba08bf09e2f525acd0");
  114. TradesSoldIncrementGetRequest req2 = new TradesSoldIncrementGetRequest(); //增量备份接口
  115. req2.setFields("total_results,has_next,trades,seller_nick,pic_path,payment,seller_rate,post_fee,receiver_name,receiver_state,receiver_address,receiver_zip,receiver_mobile"+
  116. ",receiver_phone,consign_time,received_payment,receiver_country,receiver_town,order_tax_fee,shop_pick,tid,num,num_iid,status,title,type,price,discount_fee"+
  117. ",total_fee,created,pay_time,modified,end_time,seller_flag,buyer_nick,has_buyer_message,credit_card_fee,step_trade_status,step_paid_fee,mark_desc,shipping_type"+
  118. ",adjust_fee,trade_from"+
  119. ",service_orders,oid,item_oid,service_id,service_detail_url,num,price,payment,title,total_fee,buyer_nick,refund_id,seller_nick,pic_path"+
  120. ",tmser_spu_code,oid_str,buyer_rate,receiver_city,receiver_district,o2o,o2o_guide_id,o2o_delivery,"+
  121. ",orders,item_meal_name,pic_path,seller_nick,buyer_nick,refund_status,outer_iid,snapshot_url,snapshot,timeout_action_time,buyer_rate,seller_rate"+
  122. ",seller_type,cid,sub_order_tax_fee,sub_order_tax_rate,oid,status,title,item_oid,type,sku_properties_name,order_attr,shipping_type"+
  123. ",md_qualification,customization,inv_type,shipper,f_type,f_status,f_term,assembly_rela,cl_down_payment,cl_month_payment,cl_tail_payment"+
  124. ",cl_installment_num,cal_penalty,cl_service_fee,cl_car_taker,cl_car_taker_phone,cl_car_taker_i_d_num,cl_car_taker_id_num,down_payment"+
  125. ",down_payment_ratio,month_payment,tail_payment,installment_num,penalty,service_fee,oid_str,nr_reduce_inv_fail,sort_info"+
  126. ",rt_omni_outer_sc_id,rt_omni_sc_id,modify_address,ti_modify_address_time,omni_jxs_outerid,propoint,brand_light_shop_source,special_refund_type"+
  127. ",extend_info,service_type,threepl_timing,is_o2o_passport,delivery_time,sign_time");
  128. Date date2 = new Date();
  129. Calendar calendar2 = Calendar.getInstance();
  130. calendar2.setTime(new Date());
  131. calendar2.set(Calendar.HOUR_OF_DAY, 0);
  132. calendar2.set(Calendar.MINUTE, 0);
  133. calendar2.set(Calendar.SECOND, 0);
  134. Date zero = calendar2.getTime();
  135. req2.setStartModified(zero);
  136. // req2.setStartModified(StringUtils.parseDateTime("2020-01-05 00:00:00"));
  137. calendar2.set(Calendar.HOUR_OF_DAY, 23);
  138. calendar2.set(Calendar.MINUTE, 59);
  139. calendar2.set(Calendar.SECOND, 59);
  140. Date endtime = calendar2.getTime();
  141. req2.setEndModified(endtime);
  142. // req2.setEndModified(StringUtils.parseDateTime("2020-01-05 23:59:59"));
  143. try {
  144. TradesSoldIncrementGetResponse rsp2 = client2.execute(req2, session_Key);
  145. trades = rsp2.getTrades();
  146. } catch (Exception e) {
  147. logger.info(this.getClass() + "淘宝未响应并返回订单数据");
  148. }
  149. }
  150. List<String> insertSqlsList = new ArrayList<String>();
  151. if (trades ==null || trades.size() == 0) {
  152. logger.info(this.getClass() + " 未录入淘宝订单 ");
  153. } else {
  154. int L=0;
  155. List<Long> saleIDS =new ArrayList<>();
  156. for (int i = 0; i < trades.size(); i++) {
  157. /* 插入淘宝订单ID sa_tradeid 字段 alter table sale add sa_tradeid number; */
  158. Long said = baseDao.queryForObject("select sale_seq.nextval from dual", Long.class);
  159. saleIDS.add(said);
  160. String sa_code = baseDao.sGetMaxNumber("Sale", 2);
  161. SimpleDateFormat formatdx = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
  162. String createdtime="2020-11-25";
  163. if(trades.get(i).getCreated() == null ) {
  164. createdtime = formatdx.format(new DATE());
  165. } else {
  166. createdtime = formatdx.format(trades.get(i).getCreated());
  167. }
  168. String modified="2020-11-25";
  169. if(trades.get(i).getModified() == null ) {
  170. modified = formatdx.format(trades.get(i).getCreated());
  171. } else {
  172. modified = formatdx.format(trades.get(i).getModified());
  173. }
  174. String end_time="2020-11-25";
  175. if(trades.get(i).getEndTime() == null ) {
  176. end_time = formatdx.format(trades.get(i).getCreated());
  177. } else {
  178. end_time = formatdx.format( trades.get(i).getEndTime() );
  179. }
  180. String consigntime="2020-11-25";
  181. if(trades.get(i).getConsignTime() == null ) {
  182. consigntime = formatdx.format(trades.get(i).getCreated());
  183. } else {
  184. consigntime = formatdx.format( trades.get(i).getConsignTime() );
  185. }
  186. if(trades.get(i).getConsignTime() == null ) {
  187. consigntime = formatdx.format(trades.get(i).getCreated());
  188. } else {
  189. consigntime = formatdx.format( trades.get(i).getConsignTime() );
  190. }
  191. //0819
  192. String oaid=trades.get(i).getOaid();
  193. String tid6=trades.get(i).getTid().toString();
  194. TopOaidDecryptRequest req6 = new TopOaidDecryptRequest();
  195. List<TopOaidDecryptRequest.ReceiverQuery> list2 = new ArrayList<TopOaidDecryptRequest.ReceiverQuery>();
  196. TopOaidDecryptRequest.ReceiverQuery obj3 = new TopOaidDecryptRequest.ReceiverQuery();
  197. list2.add(obj3);
  198. obj3.setOaid(oaid);
  199. obj3.setTid(tid6);
  200. obj3.setScene("1001");
  201. req6.setQueryList(list2);
  202. TaobaoClient client6 = new DefaultTaobaoClient("http://39.98.201.114:30001/router/rest", "31921866", "7121c52d4c9970ba08bf09e2f525acd0");
  203. String name_oaid=trimNull(trades.get(i).getReceiverName() );
  204. String receiver_mobile=trimNull(trades.get(i).getReceiverMobile() );
  205. String address=trimNull(trades.get(i).getReceiverState() ) + trimNull(trades.get(i).getReceiverCity() ) + trimNull(trades.get(i).getReceiverDistrict() ) + trimNull( trades.get(i).getReceiverAddress() );
  206. if(oaid!=null) {
  207. try {
  208. TopOaidDecryptResponse rsp6 = client6.execute(req6, session_Key);
  209. name_oaid=rsp6.getReceiverList().get(0).getName();
  210. receiver_mobile=rsp6.getReceiverList().get(0).getMobile();
  211. address=trimNull(rsp6.getReceiverList().get(0).getState() ) + trimNull(rsp6.getReceiverList().get(0).getCity() ) + trimNull(rsp6.getReceiverList().get(0).getDistrict() ) + trimNull( rsp6.getReceiverList().get(0).getAddressDetail() );
  212. } catch (Exception e) {
  213. logger.info(new SimpleDateFormat("YYYY-MM-DD hh24:mm:ss").format(new Date()) + this.getClass() + "淘宝未返回敏感数据");
  214. }
  215. }
  216. //
  217. String INSERTSALESql = "insert into sale( SA_ISUPDATE,SA_DISCOUNTFEE,SA_TRADESTATUS, sa_sellernick,sa_custcode,sa_paymentscode,SA_TAOBAOID,sa_payments,sa_custname,sa_kind,sa_wwh_user,sa_need15,sa_id,sa_tradeid,sa_code,sa_date,sa_recorder,sa_recorddate,sa_currency,sa_rate" +
  218. ",sa_apcustname,sa_need9,sa_toplace" +
  219. ",sa_transport,sa_seller,sa_updatedate" +
  220. ",sa_enddate,sa_statuscode,sa_status,sa_fare,sa_total" +
  221. ",sa_recamount,sa_plandelivery,sa_printstatuscode,sa_remark)" +
  222. " SELECT 1,"+trades.get(i).getDiscountFee() +",'"+trimNull(trades.get(i).getStatus() )+"','" + trimNull(trades.get(i).getSellerNick() ) + " ', 'GN0008358','P001', " + trades.get(i).getTid() + " , '现结','HLK淘宝','国内标准销售订单', ' " +trimNull( name_oaid ) + " ' , ' " + trimNull( receiver_mobile ) + " ' , " + said + "," + trades.get(i).getTid() + "," + trades.get(i).getTid()
  223. + " , to_date ( '" + end_time + "' ,'YYYY-MM-DD hh24:mi:ss') , '管理员',sysdate,'RMB','1','"
  224. + trimNull(name_oaid )+ "','" + trimNull( trades.get(i).getBuyerNick() )+ "','" + address + " ', ' "
  225. + trimNull( trades.get(i).getShippingType() ) + " ', ' " + trimNull (trades.get(i).getO2oGuideName() ) + " ', to_date ( '" + modified
  226. + "','YYYY-MM-DD hh24:mi:ss') , to_date ( '" +end_time + "','YYYY-MM-DD hh24:mi:ss') ,'ENTERING','在录入'," + trimNull( trades.get(i).getPostFee() )+ "," +trimNull( trades.get(i).getPayment() ) + ","
  227. + trimNull(trades.get(i).getPayment() ) + " , to_date ( '" +consigntime + "','YYYY-MM-DD hh24:mi:ss') ,'unprint', '淘宝自动抓取' FROM DUAL " +
  228. " WHERE '" + trimNull(trades.get(i).getStatus() ) + "' NOT IN ( 'TRADE_NO_CREATE_PAY','WAIT_BUYER_PAY','PAY_PENDING' ) AND NOT EXISTS ( select sa_id from sale WHERE SA_iD=" + said + " ) AND NOT EXISTS ( select SA_CODE from sale WHERE SA_CODE= '" + trades.get(i).getTid() + "' ) AND NOT EXISTS ( select SA_TAOBAOID from sale WHERE SA_TAOBAOID=" + trades.get(i).getTid() + " ) ";
  229. insertSqlsList.add(INSERTSALESql);
  230. List<Order> orders = trades.get(i).getOrders();
  231. for (int j = 0; j < orders.size(); j++) {
  232. int k = j + 1;
  233. L++;
  234. Long sdid = baseDao.queryForObject("select saledetail_seq.nextval from dual", Long.class);
  235. String INSERTSALEDETAILSql = "insert into saledetail(SD_PROPERTIES,sd_remark,sd_id,sd_said,sd_code,sd_detno,sd_prodcode,sd_qty,sd_price,sd_total" +
  236. ",sd_statuscode,sd_status,sd_discount,SD_DIVIDE_ORDER_FEE,SD_PART_MJZ_DISCOUNT )" +
  237. " SELECT ' " + trimNull ( orders.get(j).getSkuPropertiesName() ) + " ' , ' " + orders.get(j).getTitle() + " ' , " + sdid + " ," + said + " ,' " + sdid + " '," + k + ",'" + trimNull(orders.get(j).getOuterIid()) + "'," + orders.get(j).getNum() + "," + orders.get(j).getPrice() + " ," + orders.get(j).getPayment() +
  238. ",'ENTERING','在录入', " + orders.get(j).getDiscountFee() +","+orders.get(j).getDivideOrderFee() +","+orders.get(j).getPartMjzDiscount() + " FROM DUAL WHERE NOT EXISTS ( select sd_id from saledetail " +
  239. "WHERE '" + trimNull(trades.get(i).getStatus() ) + "' NOT IN ( 'TRADE_NO_CREATE_PAY','WAIT_BUYER_PAY','PAY_PENDING' ) AND sd_id=" + sdid + " ) AND NOT EXISTS ( select sd_id from sale left join saledetail on sa_id=sd_said " +
  240. "WHERE SA_TAOBAOID = " + trades.get(i).getTid() + " and sd_detno = " + k +" ) ";
  241. insertSqlsList.add(INSERTSALEDETAILSql);
  242. }
  243. }
  244. try{
  245. baseDao.execute(insertSqlsList);
  246. if(saleIDS.size()>0) {
  247. baseDao.callProcedure("SP_UPDATE_SALE", StringUtils.join(saleIDS, ','));
  248. }
  249. }catch (Exception e) {
  250. logger.info( e.getMessage() );
  251. }
  252. }
  253. logger.info(this.getClass() + "插入销售明细成功");
  254. }
  255. }
  256. }