package com.xinghuo.service.api.wayfair;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.xinghuo.framework.auth.util.UserUtils; import com.xinghuo.framework.core.util.HttpUtil; import com.xinghuo.framework.core.util.ResultData; import com.xinghuo.service.api.eagle.EagleApi; import com.xinghuo.service.basic.entity.*; import com.xinghuo.service.basic.server.mapper.*; import com.xinghuo.service.basic.server.service.BasOrderGenerationRuleService; import com.xinghuo.service.common.util.HttpRequestMethedEnum; import okhttp3.*; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.interceptor.TransactionAspectSupport; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*;
@RestController @RequestMapping("/wayfair") public class WayfairApi {
@Value("${wayfair.clientId}") private String clientId;
@Value("${wayfair.clientSecret}") private String clientSecret;
@Value("${wayfair.apiUrl}") private String apiUrl;
@Value("${wayfair.authUrl}") private String authUrl;
@Value("${wayfair.sandboxClientId}") private String sandboxClientId;
@Value("${wayfair.sandboxClientSecret}") private String sandboxClientSecret;
@Value("${wayfair.sandboxApiUrl}") private String sandboxApiUrl;
@Autowired private OrderApiMapper orderApiMapper; @Autowired private OrderDetailApiMapper orderDetailApiMapper; @Autowired private ReturnApiMapper returnApiMapper; @Autowired private ReturnDetailApiMapper returnDetailApiMapper; @Autowired private CommonMapper commonMapper; @Autowired private BasOrderGenerationRuleService basOrderGenerationRuleService; @Autowired private OutboundMasterMapper outboundMasterMapper; @Autowired private OutboundDetailMapper outboundDetailMapper; @Autowired private EagleApi eagleApi;
/** * 通过okhttp3 Java库发送HTTP请求的Helper函数。 * * @param method: HTTP请求方法(POST, GET, PUT, DELETE等) * @param url: 请求的url * @param body: 请求的有效负载(如果适用) * @param headers: 请求的报头(授权、内容类型、缓存控制等) * @return 响应 * @throws IOException */ private static String sendRequest(String method, String url, String body, Map<String, String> headers) throws Exception { Response response = null; OkHttpClient client = new OkHttpClient(); RequestBody requestBody = RequestBody.create(contentType, body); Headers.Builder headerBuilder = new Headers.Builder(); for (String key : headers.keySet()) { headerBuilder.add(key, headers.get(key)); } Request.Builder requestBuilder = new Request.Builder() .url(url) .headers(headerBuilder.build()); if (method.equals("POST")) requestBuilder.post(requestBody); Request request = requestBuilder.build(); try { response = client.newCall(request).execute(); } catch (Exception ex) { throw new Exception("Request failed with response " + ex.getMessage()); } return response.body().string(); }
/** * 基于Content-Type的静态媒体类型 * 注意:如果请求的Content-Type与JSON不同,这将会改变。 */ private static final MediaType contentType = MediaType.parse("application/json; charset=utf-8");
/** * 函数用于根据客户端的id和secret获取身份验证令牌。令牌稍后会 * 以“承载{TOKEN}”的格式传递到HTTP请求的认证头中。如果 * 请求抛出异常或用户无法通过身份验证,则该函数将返回None,并将错误打印到控制台。 * * @param clientID : 客户端ID * @param clientSecret :客户的秘密 * @return response */ private static String fetchToken(String clientID, String clientSecret, String authUrl) { Map map = null; String payload = "{\"grant_type\":\"client_credentials\",\"client_id\":\"" + clientID + "\",\"client_secret\": \"" + clientSecret + "\", \"audience\": \"https://api.wayfair.com/\"}"; String method = "POST"; Map<String, String> headers = new HashMap<>(); headers.put("content-type", "application/json"); headers.put("cache-control", "no-cache"); try { String jsonResult = sendRequest(method, authUrl, payload, headers); if (null == jsonResult) { System.out.println("find Token failed"); } map = JSONObject.parseObject(jsonResult, Map.class); } catch (Exception ex) { System.out.println("Could not retrieve a token for the request: " + ex.getMessage()); } return map.get("access_token").toString(); }
/** * 获取半年前的销售订单 */ @RequestMapping("/getOrders") @Transactional public ResultData getOrders() { //获取授权token String token = fetchToken(clientId, clientSecret, authUrl); if (token == null) { return ResultData.fail("Token Request failed."); } OrderApi orderApi1 = new OrderApi(); orderApi1.setPlatform("Wayfair"); List<OrderApi> orders = orderApiMapper.query(orderApi1); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date now = new Date(); //半年前 Calendar instance = Calendar.getInstance(); instance.setTime(new Date()); instance.add(Calendar.MONTH, -6); Date time = instance.getTime(); String fromDate = simpleDateFormat.format(time); String response = ""; String method = "POST"; String graphqlQuery = ""; String query = "query getDropshipPurchaseOrders {getDropshipPurchaseOrders (limit: 2000,hasResponse: false,fromDate: \\\"" + fromDate + "\\\",sortOrder: DESC) {poNumber,poDate,estimatedShipDate,customerName,customerAddress1,customerAddress2,customerCity,customerState,customerPostalCode,orderType,shippingInfo {shipSpeed,carrierCode},packingSlipUrl,warehouse {id,name,address {name,address1,address2,address3,city,state,country,postalCode}},products {partNumber,quantity,price,event {id,type,name,startDate,endDate}},shipTo {name,address1,address2,address3,city,state,country,postalCode,phoneNumber}}}"; String variables = "{}"; Map<String, String> headers = new HashMap<>(); headers.put("content-type", "application/json"); headers.put("cache-control", "no-cache"); headers.put("authorization", "Bearer " + token); JSONObject variablesObj = null; try { if (variables != null) { variablesObj = new JSONObject(Boolean.parseBoolean(variables)); graphqlQuery = "{\"query\": \"" + query + "\",\"variables\":" + variablesObj.toString() + "}"; } else { graphqlQuery = "{\"query\": \"" + query + "\",\"variables\":" + variables + "}"; } } catch (Exception ex) { return ResultData.fail("Graph QL variable JSON parsing failed with response: " + ex.getMessage()); } try { response = sendRequest(method, apiUrl, graphqlQuery, headers); } catch (Exception ex) { return ResultData.fail("Problem executing the GraphQL Request: " + ex.getMessage()); } JSONObject resultObject = JSONObject.parseObject(response); Map data = (Map) resultObject.get("data"); if (null == data) { return ResultData.fail("请求异常" + response); } List<Map<String, Object>> getDropshipPurchaseOrders = (List<Map<String, Object>>) data.get("getDropshipPurchaseOrders"); List<OrderApi> orderApiList = new ArrayList<>(); List<OrderDetailApi> orderDetailApiList = new ArrayList<>(); if (!CollectionUtils.isEmpty(getDropshipPurchaseOrders)) { Date date = new Date(); String userCode = UserUtils.getUserCode(); for (Map<String, Object> order : getDropshipPurchaseOrders) { OrderApi orderApi = new OrderApi(); //订单信息 String poNumber = (String) order.get("poNumber"); Optional<OrderApi> first = orders.stream().filter(he -> he.getPo().equals(poNumber)).findFirst(); if (first.isPresent()) { continue; } String poDateStr = (String) order.get("poDate"); poDateStr = poDateStr.substring(0, 19); Date poDate = null; try { poDate = simpleDateFormat.parse(poDateStr); } catch (ParseException e) { e.printStackTrace(); return ResultData.fail("时间转化异常" + poDateStr); } String estimatedShipDateStr = (String) order.get("estimatedShipDate"); estimatedShipDateStr = estimatedShipDateStr.substring(0, 19); Date estimatedShipDate = null; try { estimatedShipDate = simpleDateFormat.parse(estimatedShipDateStr); } catch (ParseException e) { e.printStackTrace(); return ResultData.fail("时间转化异常" + estimatedShipDateStr); } //客户信息 String customerName = (String) order.get("customerName"); String customerAddress1 = (String) order.get("customerAddress1"); String customerAddress2 = (String) order.get("customerAddress2"); String customerCity = (String) order.get("customerCity"); String customerState = (String) order.get("customerState"); String customerEmail = (String) order.get("customerEmail"); //运输 Map shippingInfo = (Map) order.get("shippingInfo"); String shipSpeed = (String) shippingInfo.get("shipSpeed"); String carrierCode = (String) shippingInfo.get("carrierCode"); //仓库 Map warehouse = (Map) order.get("warehouse"); String name = (String) warehouse.get("name"); Map address = (Map) warehouse.get("address"); String address1 = (String) address.get("address1"); Map shipTo = (Map) order.get("shipTo"); String country = (String) address.get("country"); String phoneNumber = (String) address.get("phoneNumber"); orderApi.setPo(poNumber); orderApi.setPlatform("Wayfair"); orderApi.setPoDate(poDate); orderApi.setMustShipBy(estimatedShipDate); orderApi.setShipToPhone(phoneNumber); orderApi.setShipMethod(""); orderApi.setShipToName(customerName); orderApi.setShipToAddressOne(customerAddress1); orderApi.setShipToAddressTwo(customerAddress2); orderApi.setShipToCity(customerCity); orderApi.setShipToState(customerState); orderApi.setShipToCountry(country); orderApi.setShipToZip(customerEmail); orderApi.setCarrierName(carrierCode); orderApi.setCreateTime(date); orderApi.setCreateUser(userCode); orderApi.setStatus(""); orderApi.setIsHistory("0"); orderApi.setIsOperation("1"); List<Map<String, Object>> products = (List<Map<String, Object>>) order.get("products"); if (!CollectionUtils.isEmpty(products)) { int rowNum = 0; for (Map<String, Object> product : products) { rowNum = rowNum + 1; String sku = (String) product.get("partNumber"); String quantity = (String) product.get("quantity"); System.out.println("po为" + poNumber + ":" + product.get("price").toString()); // BigDecimal price = (BigDecimal) product.get("price"); OrderDetailApi orderDetailApi = new OrderDetailApi(); orderDetailApi.setCreateTime(date); orderDetailApi.setCreateUser(userCode); orderDetailApi.setPo(poNumber); orderDetailApi.setIsHistory("0"); orderDetailApi.setRowNum(String.valueOf(rowNum)); orderDetailApi.setSku(sku); orderDetailApi.setVendor(""); orderDetailApi.setStatus(""); orderDetailApi.setPoQty(Integer.parseInt(quantity)); orderDetailApi.setPrice(Double.parseDouble(product.get("price").toString())); orderDetailApiList.add(orderDetailApi); } } orderApiList.add(orderApi); } } try { if (!CollectionUtils.isEmpty(orderApiList)) { orderApiMapper.insertBatch(orderApiList); } if (!CollectionUtils.isEmpty(orderDetailApiList)) { orderDetailApiMapper.insertBatch(orderDetailApiList); } } catch (Exception exception) { exception.getMessage(); exception.printStackTrace(); System.out.println(exception.getMessage()); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return ResultData.fail("存储数据到数据库出现异常" + exception.getMessage()); } return ResultData.succeed("api获取数据成功总共" + orderApiList.size() + "个订单"); }
/** * 获取新增的订单 */ @RequestMapping("/getOrdersNew") @Transactional public ResultData getOrdersNew() { //获取授权token String token = fetchToken(clientId, clientSecret, authUrl); if (token == null) { return ResultData.fail("Token Request failed."); } OrderApi orderApi1 = new OrderApi(); orderApi1.setPlatform("Wayfair"); List<OrderApi> orders = orderApiMapper.query(orderApi1); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date now = new Date(); Date time = orderApiMapper.orderMaxDate(orderApi1); if (time == null) { //半年前 Calendar instance = Calendar.getInstance(); instance.setTime(new Date()); instance.add(Calendar.MONTH, -1); time = instance.getTime(); } String fromDate = simpleDateFormat.format(time); String response = ""; String method = "POST"; String graphqlQuery = ""; // String query = "query getDropshipPurchaseOrders {getDropshipPurchaseOrders (limit: 2000,hasResponse: false,fromDate: \\\"" + fromDate + "\\\",sortOrder: DESC) {poNumber,poDate,estimatedShipDate,customerName,customerAddress1,customerAddress2,customerCity,customerState,customerPostalCode,orderType,shippingInfo {shipSpeed,carrierCode},packingSlipUrl,warehouse {id,name,address {name,address1,address2,address3,city,state,country,postalCode}},products {partNumber,quantity,price,event {id,type,name,startDate,endDate}},shipTo {name,address1,address2,address3,city,state,country,postalCode,phoneNumber}}}"; String query = "query getDropshipPurchaseOrders {getDropshipPurchaseOrders (limit: 2000,fromDate: \\\"" + fromDate + "\\\",sortOrder: DESC) {poNumber,poDate,estimatedShipDate,customerName,customerAddress1,customerAddress2,customerCity,customerState,customerPostalCode,orderType,shippingInfo {shipSpeed,carrierCode},packingSlipUrl,warehouse {id,name,address {name,address1,address2,address3,city,state,country,postalCode}},products {partNumber,quantity,price,event {id,type,name,startDate,endDate}},shipTo {name,address1,address2,address3,city,state,country,postalCode,phoneNumber}}}"; String variables = "{}"; Map<String, String> headers = new HashMap<>(); headers.put("content-type", "application/json"); headers.put("cache-control", "no-cache"); headers.put("authorization", "Bearer " + token); JSONObject variablesObj = null; try { if (variables != null) { variablesObj = new JSONObject(Boolean.parseBoolean(variables)); graphqlQuery = "{\"query\": \"" + query + "\",\"variables\":" + variablesObj.toString() + "}"; } else { graphqlQuery = "{\"query\": \"" + query + "\",\"variables\":" + variables + "}"; } } catch (Exception ex) { return ResultData.fail("Graph QL variable JSON parsing failed with response: " + ex.getMessage()); } try { response = sendRequest(method, apiUrl, graphqlQuery, headers); } catch (Exception ex) { return ResultData.fail("Problem executing the GraphQL Request: " + ex.getMessage()); } JSONObject resultObject = JSONObject.parseObject(response); Map data = (Map) resultObject.get("data"); if (null == data) { return ResultData.fail("请求异常" + response); } List<Map<String, Object>> getDropshipPurchaseOrders = (List<Map<String, Object>>) data.get("getDropshipPurchaseOrders"); List<OrderApi> orderApiList = new ArrayList<>(); List<OrderDetailApi> orderDetailApiList = new ArrayList<>(); if (!CollectionUtils.isEmpty(getDropshipPurchaseOrders)) { Date date = new Date(); String userCode = UserUtils.getUserCode(); for (Map<String, Object> order : getDropshipPurchaseOrders) { OrderApi orderApi = new OrderApi(); //订单信息 String poNumber = (String) order.get("poNumber"); Optional<OrderApi> first = orders.stream().filter(he -> he.getPo().equals(poNumber)).findFirst(); if (first.isPresent()) { continue; } String poDateStr = (String) order.get("poDate"); poDateStr = poDateStr.substring(0, 19); Date poDate = null; try { poDate = simpleDateFormat.parse(poDateStr); } catch (ParseException e) { e.printStackTrace(); return ResultData.fail("时间转化异常" + poDateStr); } String estimatedShipDateStr = (String) order.get("estimatedShipDate"); estimatedShipDateStr = estimatedShipDateStr.substring(0, 19); Date estimatedShipDate = null; try { estimatedShipDate = simpleDateFormat.parse(estimatedShipDateStr); } catch (ParseException e) { e.printStackTrace(); return ResultData.fail("时间转化异常" + estimatedShipDateStr); } //客户信息 String customerName = (String) order.get("customerName"); String customerAddress1 = (String) order.get("customerAddress1"); String customerAddress2 = (String) order.get("customerAddress2"); String customerCity = (String) order.get("customerCity"); String customerState = (String) order.get("customerState"); String customerEmail = (String) order.get("customerEmail"); //运输 Map shippingInfo = (Map) order.get("shippingInfo"); String shipSpeed = (String) shippingInfo.get("shipSpeed"); String carrierCode = (String) shippingInfo.get("carrierCode"); //仓库 Map warehouse = (Map) order.get("warehouse"); String name = (String) warehouse.get("name"); Map address = (Map) warehouse.get("address"); String address1 = (String) address.get("address1"); Map shipTo = (Map) order.get("shipTo"); String country = (String) address.get("country"); String phoneNumber = (String) address.get("phoneNumber"); orderApi.setPo(poNumber); orderApi.setPlatform("Wayfair"); orderApi.setPoDate(poDate); orderApi.setMustShipBy(estimatedShipDate); orderApi.setShipToPhone(phoneNumber); orderApi.setShipMethod(""); orderApi.setShipToName(customerName); orderApi.setShipToAddressOne(customerAddress1); orderApi.setShipToAddressTwo(customerAddress2); orderApi.setShipToCity(customerCity); orderApi.setShipToState(customerState); orderApi.setShipToCountry(country); orderApi.setShipToZip(customerEmail); orderApi.setCarrierName(carrierCode); orderApi.setCreateTime(date); orderApi.setCreateUser(userCode); orderApi.setStatus(""); orderApi.setIsHistory("0"); orderApi.setIsOperation("0"); List<Map<String, Object>> products = (List<Map<String, Object>>) order.get("products"); if (!CollectionUtils.isEmpty(products)) { int rowNum = 0; for (Map<String, Object> product : products) { rowNum = rowNum + 1; String sku = (String) product.get("partNumber"); String quantity = (String) product.get("quantity"); System.out.println("po为" + poNumber + ":" + product.get("price").toString()); // BigDecimal price = (BigDecimal) product.get("price"); OrderDetailApi orderDetailApi = new OrderDetailApi(); orderDetailApi.setCreateTime(date); orderDetailApi.setCreateUser(userCode); orderDetailApi.setPo(poNumber); orderDetailApi.setIsHistory("0"); orderDetailApi.setRowNum(String.valueOf(rowNum)); orderDetailApi.setSku(sku); orderDetailApi.setVendor(""); orderDetailApi.setStatus(""); orderDetailApi.setPoQty(Integer.parseInt(quantity)); orderDetailApi.setPrice(Double.parseDouble(product.get("price").toString())); orderDetailApiList.add(orderDetailApi); } } orderApiList.add(orderApi); } } try { if (!CollectionUtils.isEmpty(orderApiList)) { orderApiMapper.insertBatch(orderApiList); } if (!CollectionUtils.isEmpty(orderDetailApiList)) { orderDetailApiMapper.insertBatch(orderDetailApiList); } } catch (Exception exception) { exception.getMessage(); exception.printStackTrace(); System.out.println(exception.getMessage()); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return ResultData.fail("存储数据到数据库出现异常" + exception.getMessage()); } return ResultData.succeed("api获取数据成功总共" + orderApiList.size() + "个订单"); }
/** * 接单 */ @RequestMapping("/acknowledge") @Transactional public ResultData acknowledge(OrderApi orderApi) { //获取授权token // String token = fetchToken(clientId, clientSecret, authUrl); String token = fetchToken(sandboxClientId, sandboxClientSecret, authUrl); if (token == null) { return ResultData.fail("Token Request failed."); } SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String purchaseOrderId = orderApi.getPo(); String platform = orderApi.getPlatform(); if (null == platform || StringUtils.isBlank(platform)) { return ResultData.fail("请传入平台"); } else { if (!platform.equals("Wayfair")) { return ResultData.fail("订单平台不一致" + platform); } } //运输方式后期可能要支持页面上选择 String shipSpeedType = orderApi.getShipSpeedType(); if (StringUtils.isBlank(shipSpeedType)) { return ResultData.fail("请选择运输方式"); } else { Common common = new Common(); List<Common> commons = commonMapper.speedTypeList(common); Optional<Common> first = commons.stream().filter(he -> he.getCode().equals(shipSpeedType)).findFirst(); if (!first.isPresent()) { return ResultData.fail("运输方式有误" + shipSpeedType); } } if (null == purchaseOrderId || StringUtils.isBlank(purchaseOrderId)) { return ResultData.fail("请传入订单号"); } // String detailStr = orderApi.getDetailStr(); // List<OrderDetailApi> detail = JSONArray.parseArray(detailStr, OrderDetailApi.class); // if (CollectionUtils.isEmpty(detail)) { // return ResultData.fail("请传入要取消的要取消的明细数据"); // } List<OrderApi> orders = orderApiMapper.query(orderApi); if (orders.size() > 1) { return ResultData.fail("抓取API的订单" + purchaseOrderId + "出现重复,请仔细核对"); } if (CollectionUtils.isEmpty(orders)) { return ResultData.fail("系统没有查到有关于这个" + purchaseOrderId + "的订单信息"); } OrderApi orderApi1 = orders.get(0); OrderDetailApi detailApi1 = new OrderDetailApi(); detailApi1.setPo(purchaseOrderId); List<OrderDetailApi> detail = orderDetailApiMapper.query(detailApi1); if (CollectionUtils.isEmpty(detail)) { return ResultData.fail("系统没有查到有关于这个" + purchaseOrderId + "的明细信息"); } String lineItems = ""; for (OrderDetailApi detailApi : detail) { String sku = detailApi.getSku(); Integer poQty = detailApi.getPoQty(); Double price = detailApi.getPrice(); Calendar instance = Calendar.getInstance(); instance.setTime(new Date()); instance.add(Calendar.DATE, 5); Date time = instance.getTime(); detailApi.setEstimatedShipDate(time); Date estimatedShipDate = detailApi.getEstimatedShipDate(); String nestimatedShipDateStr = simpleDateFormat.format(estimatedShipDate); String itemStr = "\\n{\\npartNumber: \\\"%s\\\",\\nquantity: %d,\\nunitPrice: %f,\\nestimatedShipDate: \\\"%s\\\"\\n}\\n"; String format = String.format(itemStr, sku, poQty, price, nestimatedShipDateStr); lineItems = lineItems + format + ","; } String response = ""; String method = "POST"; String graphqlQuery = ""; String query = "mutation accept {\\npurchaseOrders {\\naccept (\\npoNumber: \\\"%s\\\",\\nshipSpeed: %s,\\nlineItems: [%s]\\n) {\\nhandle,\\nsubmittedAt,\\nerrors {\\nkey,\\nmessage\\n}\\n}\\n}\\n}"; query = String.format(query, purchaseOrderId, shipSpeedType, lineItems); String variables = "{}"; Map<String, String> headers = new HashMap<>(); headers.put("content-type", "application/json"); headers.put("cache-control", "no-cache"); headers.put("authorization", "Bearer " + token); JSONObject variablesObj = null; try { if (variables != null) { variablesObj = new JSONObject(Boolean.parseBoolean(variables)); graphqlQuery = "{\"query\": \"" + query + "\",\"variables\":" + variablesObj.toString() + "}"; } else { graphqlQuery = "{\"query\": \"" + query + "\",\"variables\":" + variables + "}"; } } catch (Exception ex) { return ResultData.fail("Graph QL variable JSON parsing failed with response: " + ex.getMessage()); } try { response = sendRequest(method, sandboxApiUrl, graphqlQuery, headers); // response = sendRequest(method, apiUrl, graphqlQuery, headers); } catch (Exception ex) { return ResultData.fail("Problem executing the GraphQL Request: " + ex.getMessage()); } JSONObject resultObject = JSONObject.parseObject(response); System.out.println(response); Map data = (Map) resultObject.get("data"); if (null == data) { return ResultData.fail(response); } Map purchaseOrders = (Map) data.get("purchaseOrders"); Map accept = (Map) purchaseOrders.get("accept"); List<Map<String, Object>> errors = (List<Map<String, Object>>) accept.get("errors"); if (!CollectionUtils.isEmpty(errors)) { return ResultData.fail(errors.get(0).get("message").toString()); } else { Date date = new Date(); String userCode = UserUtils.getUserCode(); // OrderApi orderApi2 = new OrderApi(); orderApi1.setStatus("Acknowledged"); orderApi1.setUpdateTime(date); orderApi1.setUpdateUser(userCode); orderApi1.setIsOperation("1"); OrderDetailApi orderDetailApi = new OrderDetailApi(); orderDetailApi.setPo(purchaseOrderId); orderDetailApi.setStatus("Acknowledged"); orderDetailApi.setUpdateTime(date); orderDetailApi.setUpdateUser(userCode); try { orderApiMapper.update(orderApi1); orderDetailApiMapper.update(orderDetailApi); List<OutboundMaster> outboundMasters = new ArrayList<>(); List<OutboundDetail> outboundDetails = new ArrayList<>(); int i = 0; for (OrderDetailApi orderDetailApi1 : detail) { for (int j = 0; j < orderDetailApi1.getPoQty(); j++) { i = i + 1; OutboundMaster outboundMaster1 = new OutboundMaster(); ResultData<String> orderData = basOrderGenerationRuleService.orderGeneration("out_warehousing_order", UserUtils.getUserCode()); if (orderData.getCode() != 200) return orderData; String orderNum = orderData.getData(); outboundMaster1.setOrder(orderNum); outboundMaster1.setPo(purchaseOrderId + "-" + i); outboundMaster1.setOrderType("API"); outboundMaster1.setPoDate(orderApi1.getPoDate()); outboundMaster1.setPlatform(orderApi1.getPlatform()); outboundMaster1.setMustShipBy(orderApi1.getMustShipBy()); outboundMaster1.setStatus("0"); outboundMaster1.setShipMethod(orderApi1.getShipMethod()); outboundMaster1.setCarrierName(orderApi1.getCarrierName()); outboundMaster1.setShippingAccountNumber(orderApi1.getShippingAccountNumber()); outboundMaster1.setShipToName(orderApi1.getShipToName()); outboundMaster1.setShipToAddressOne(orderApi1.getShipToAddressOne()); outboundMaster1.setShipToAddressTwo(orderApi1.getShipToAddressTwo()); outboundMaster1.setShipToAddressThree(orderApi1.getShipToAddressThree()); outboundMaster1.setShipToCity(orderApi1.getShipToCity()); outboundMaster1.setShipToZip(orderApi1.getShipToZip()); outboundMaster1.setShipToPhone(orderApi1.getShipToPhone()); outboundMaster1.setShipToCountry(orderApi1.getShipToCountry()); outboundMaster1.setShipToState(orderApi1.getShipToState()); outboundMaster1.setTrackingNumber(orderApi1.getTrackingNumber()); outboundMaster1.setRemark(orderApi1.getRemark()); outboundMaster1.setCreateTime(date); outboundMaster1.setCreateUser(userCode); outboundMaster1.setIsHistory("0"); outboundMaster1.setAuditBatch(1); OutboundDetail outboundDetail = new OutboundDetail(); outboundDetail.setOrder(orderNum); outboundDetail.setSku(orderDetailApi1.getSku()); outboundDetail.setWarehouse("WH231215001"); outboundDetail.setPrice(orderDetailApi1.getPrice()); outboundDetail.setPoQty(1); outboundDetail.setOutQty(0); outboundDetail.setDifferenceQty(0); outboundDetail.setVendor(orderDetailApi1.getVendor()); outboundDetail.setRemark(orderDetailApi1.getRemark()); outboundDetail.setCreateUser(userCode); outboundDetail.setCreateTime(date); outboundDetail.setIsHistory("0"); outboundMasters.add(outboundMaster1); outboundDetails.add(outboundDetail); List<OutboundDetail> outboundDetailList = new ArrayList<>(); outboundDetailList.add(outboundDetail); outboundMaster1.setDetailList(outboundDetailList); ResultData order1 = eagleApi.createWayfairOrder(outboundMaster1); if (order1.getCode() != 200) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return ResultData.fail("将数据回写到鹰仓时出现了异常" + order1.getData()); } System.out.println(order1); } } outboundMasterMapper.insertBatch(outboundMasters); outboundDetailMapper.insertBatch(outboundDetails); } catch (Exception exception) { exception.getStackTrace(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return ResultData.fail("接单成功,但是数据在转成销售出库单的时候出现了异常,请联系管理员" + exception.getMessage()); } } return ResultData.succeed(purchaseOrderId + "接单成功"); }
/** * 拒单 */ @RequestMapping("/cancel") @Transactional public ResultData cancel(OrderApi orderApi) { //获取授权token // String token = fetchToken(clientId, clientSecret, authUrl); String token = fetchToken(sandboxClientId, sandboxClientSecret, authUrl); if (token == null) { return ResultData.fail("Token Request failed."); } SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String purchaseOrderId = orderApi.getPo(); String platform = orderApi.getPlatform(); if (null == platform || StringUtils.isBlank(platform)) { return ResultData.fail("请传入平台"); } else { if (!platform.equals("Wayfair")) { return ResultData.fail("订单平台不一致" + platform); } } if (null == purchaseOrderId || StringUtils.isBlank(purchaseOrderId)) { return ResultData.fail("请传入订单号"); } // String detailStr = orderApi.getDetailStr(); // List<OrderDetailApi> detail = JSONArray.parseArray(detailStr, OrderDetailApi.class); // if (CollectionUtils.isEmpty(detail)) { // return ResultData.fail("请传入要取消的要取消的明细数据"); // } List<OrderApi> orders = orderApiMapper.query(orderApi); if (orders.size() > 1) { return ResultData.fail("抓取API的订单" + purchaseOrderId + "出现重复,请仔细核对"); } if (CollectionUtils.isEmpty(orders)) { return ResultData.fail("系统没有查到有关于这个" + purchaseOrderId + "的订单信息"); } OrderApi orderApi1 = orders.get(0); OrderDetailApi detailApi1 = new OrderDetailApi(); detailApi1.setPo(purchaseOrderId); List<OrderDetailApi> detail = orderDetailApiMapper.query(detailApi1); if (CollectionUtils.isEmpty(detail)) { return ResultData.fail("系统没有查到有关于这个" + purchaseOrderId + "的明细信息"); } String lineItems = ""; for (OrderDetailApi detailApi : detail) { String sku = detailApi.getSku(); Integer poQty = detailApi.getPoQty(); String itemStr = "\\n{\\npartNumber: \\\"%s\\\",\\nquantity: %d\\n}\\n"; String format = String.format(itemStr, sku, poQty); lineItems = lineItems + format + ","; } String response = ""; String method = "POST"; String graphqlQuery = ""; String query = "mutation reject {\\npurchaseOrders {\\nreject (\\npoNumber: \\\"%s\\\",\\nlineItems: [%s]\\n) {\\nhandle,\\nsubmittedAt,\\nerrors {\\nkey,\\nmessage\\n}\\n}\\n}\\n}"; query = String.format(query, purchaseOrderId, lineItems); String variables = "{}"; Map<String, String> headers = new HashMap<>(); headers.put("content-type", "application/json"); headers.put("cache-control", "no-cache"); headers.put("authorization", "Bearer " + token); JSONObject variablesObj = null; try { if (variables != null) { variablesObj = new JSONObject(Boolean.parseBoolean(variables)); graphqlQuery = "{\"query\": \"" + query + "\",\"variables\":" + variablesObj.toString() + "}"; } else { graphqlQuery = "{\"query\": \"" + query + "\",\"variables\":" + variables + "}"; } } catch (Exception ex) { return ResultData.fail("Graph QL variable JSON parsing failed with response: " + ex.getMessage()); } try { response = sendRequest(method, sandboxApiUrl, graphqlQuery, headers); // response = sendRequest(method, apiUrl, graphqlQuery, headers); } catch (Exception ex) { return ResultData.fail("Problem executing the GraphQL Request: " + ex.getMessage()); } JSONObject resultObject = JSONObject.parseObject(response); Map data = (Map) resultObject.get("data"); if (null == data) { return ResultData.fail(response); } System.out.println(response); Map purchaseOrders = (Map) data.get("purchaseOrders"); Map accept = (Map) purchaseOrders.get("reject"); List<Map<String, Object>> errors = (List<Map<String, Object>>) accept.get("errors"); if (!CollectionUtils.isEmpty(errors)) { return ResultData.fail(errors.get(0).get("message").toString()); } else { Date date = new Date(); String userCode = UserUtils.getUserCode(); try { orderApi1.setStatus("Cancelled"); orderApi1.setUpdateTime(date); orderApi1.setUpdateUser(userCode); orderApi1.setIsOperation("1"); OrderDetailApi orderDetailApi = new OrderDetailApi(); orderDetailApi.setPo(purchaseOrderId); orderDetailApi.setStatus("Cancelled"); orderDetailApi.setUpdateTime(date); orderDetailApi.setUpdateUser(userCode); orderApiMapper.update(orderApi1); orderDetailApiMapper.update(orderDetailApi); } catch (Exception exception) { exception.getStackTrace(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return ResultData.fail("拒单成功,但是数据在转成销售出库单的时候出现了异常,请联系管理员" + exception.getMessage()); } } return ResultData.succeed(purchaseOrderId + "拒单成功"); }
/** * 库存同步 */ @RequestMapping("/feeds") @Transactional public ResultData feeds(Inventory inventory) { //获取授权token String token = fetchToken(sandboxClientId, sandboxClientSecret, authUrl); if (token == null) { return ResultData.fail("Token Request failed."); } inventory.setInventoryStr("[{\"storeCode\":\"95501\",\"sku\":\"XXXXXXXX\",\"storeUseQty\":1}{\"storeCode\":\"95501\",\"sku\":\"XXXXXXXX\",\"storeUseQty\":2},]"); String detailStr = inventory.getInventoryStr(); List<Inventory> detail = JSONArray.parseArray(detailStr, Inventory.class); if (CollectionUtils.isEmpty(detail)) { return ResultData.fail("请传入需要同步的库存明细数据"); } String inventorys = ""; for (Inventory item : detail) { String storeCode = item.getStoreCode(); String sku = item.getSku(); Integer qty = item.getStoreUseQty(); String itemStr = "\n{\n\"supplierId\": %s,\n\"supplierPartNumber\": \"%s\",\n\"quantityOnHand\": %d\n}\n"; String format = String.format(itemStr, storeCode, sku, qty); inventorys = inventorys + format + ","; } if (StringUtils.isNotBlank(inventorys)) { inventorys = inventorys.substring(0, inventorys.length() - 1); } String response = ""; String method = "POST"; String graphqlQuery = ""; String query = "mutation save (\\n$inventory: [inventoryInput]!,\\n$feedKind: inventoryFeedKind\\n) {\\ninventory {\\nsave (\\ninventory: $inventory,\\nfeedKind: $feedKind\\n) {\\nhandle,\\nsubmittedAt,\\nerrors {\\nkey,\\nmessage\\n}\\n}\\n}\\n}"; String variables = "{\n\"inventory\": [%s],\n\"feedKind\": \"DIFFERENTIAL\"\n}"; variables = String.format(variables, inventorys); Map<String, String> headers = new HashMap<>(); headers.put("content-type", "application/json"); headers.put("cache-control", "no-cache"); headers.put("authorization", "Bearer " + token); JSONObject variablesObj = null; try { if (variables != null) { variablesObj = JSONObject.parseObject(variables); graphqlQuery = "{\"query\": \"" + query + "\",\"variables\":" + variablesObj.toString() + "}"; } else { graphqlQuery = "{\"query\": \"" + query + "\",\"variables\":" + variables + "}"; } } catch (Exception ex) { return ResultData.fail("Graph QL variable JSON parsing failed with response: " + ex.getMessage()); } try { response = sendRequest(method, sandboxApiUrl, graphqlQuery, headers); } catch (Exception ex) { return ResultData.fail("Problem executing the GraphQL Request: " + ex.getMessage()); } JSONObject resultObject = JSONObject.parseObject(response); Map data = (Map) resultObject.get("data"); if (null == data) { return ResultData.fail(response); } System.out.println(response); Map inventoryMap = (Map) data.get("inventory"); Map save = (Map) inventoryMap.get("save"); List<Map<String, Object>> errors = (List<Map<String, Object>>) save.get("errors"); if (!CollectionUtils.isEmpty(errors)) { return ResultData.fail(errors.get(0).get("message").toString()); } return ResultData.succeed("库存数据同步成功"); }
/** * 获取标签 */ @RequestMapping("/shippingLabel") public ResultData shippingLabel(String purchaseOrderNumber) throws URISyntaxException, IOException { //获取授权token String token = fetchToken(sandboxClientId, sandboxClientSecret, authUrl); if (token == null) { return ResultData.fail("Token Request failed."); } // HttpGet request = new HttpGet("https://api.wayfair.com/v1/shipping_label/" + purchaseOrderNumber); HttpGet request = new HttpGet("https://sandbox.api.wayfair.com/v1/shipping_label/" + purchaseOrderNumber); request.setHeader("Accept", "application/json"); request.setHeader("Authorization", "Bearer " + token); request.setHeader("Content-Type", "application/json"); HttpClient client = HttpClients.createDefault(); HttpResponse response = client.execute(request); // Map<String, String> headers = new HashMap<>(); // headers.put("Accept", "application/json"); // headers.put("Authorization", "Bearer " + token); // headers.put("Content-Type","application/json"); // Map<String, Object> objectObjectHashMap = new HashMap<>(); // String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpGet, "https://api.wayfair.com/v1/shipping_label/" + purchaseOrderNumber, objectObjectHashMap, headers); InputStream in = response.getEntity().getContent(); FileOutputStream out = new FileOutputStream("D:/uploadFile/shippingLabel.pdf"); byte[] buffer = new byte[1024]; int readByte = 0; //读取旧文件的流写入新文件里 while ((readByte = in.read(buffer)) != -1) { out.write(buffer, 0, readByte); } in.close(); out.close(); return ResultData.succeed(EntityUtils.toString(response.getEntity(), "UTF-8")); // return ResultData.succeed("success"); }
/** * 获取标签 */ @RequestMapping("/billOfLadingRetrieval") public ResultData billOfLadingRetrieval(String purchaseOrderNumber) throws URISyntaxException, IOException { //获取授权token String token = fetchToken(clientId, clientSecret, authUrl); if (token == null) { return ResultData.fail("Token Request failed."); } HttpGet request = new HttpGet("https://api.wayfair.com/v1/bill_of_lading/" + purchaseOrderNumber); request.setHeader("Accept", "application/json"); request.setHeader("Authorization", "Bearer " + token); request.setHeader("Content-Type", "application/json"); HttpClient client = HttpClients.createDefault(); HttpResponse response = client.execute(request); InputStream in = response.getEntity().getContent(); FileOutputStream out = new FileOutputStream("D:/uploadFile/label.pdf"); byte[] buffer = new byte[2097152]; int readByte = 0; //读取旧文件的流写入新文件里 while ((readByte = in.read(buffer)) != -1) { out.write(buffer, 0, readByte); } in.close(); out.close(); // return ResultData.succeed(EntityUtils.toString(response.getEntity(), "UTF-8")); return ResultData.succeed("success"); } }
|