package com.xinghuo.service.api.walmart;
import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import com.alibaba.fastjson.JSONObject; import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64; 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 org.apache.commons.lang3.StringUtils; 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 org.springframework.web.multipart.MultipartFile;
import java.math.BigDecimal; import java.net.URISyntaxException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*;
@RestController @RequestMapping("/walmart") public class WalmartApi {
@Value("${walmart.clientId}") private String clientId;
@Value("${walmart.clientSecret}") private String clientSecret;
@Value("${walmart.accountName}") private String accountName;
@Value("${walmart.tokenUrl}") private String tokenUrl;
@Value("${walmart.sandboxClientId}") private String sandboxClientId;
@Value("${walmart.sandboxClientSecret}") private String sandboxClientSecret;
// @Value("${walmart.accountName}") // private String accountName;
@Value("${walmart.sandboxTokenUrl}") private String sandboxTokenUrl;
@Autowired private OrderApiMapper orderApiMapper; @Autowired private OrderDetailApiMapper orderDetailApiMapper; @Autowired private ReturnApiMapper returnApiMapper; @Autowired private ReturnDetailApiMapper returnDetailApiMapper; @Autowired private BasOrderGenerationRuleService basOrderGenerationRuleService; @Autowired private OutboundMasterMapper outboundMasterMapper; @Autowired private OutboundDetailMapper outboundDetailMapper; @Autowired private EagleApi eagleApi;
/** * 对密钥进行编码 * * @return */ private String getAuthorization(String clientId, String clientSecret) { String str = clientId + ":" + clientSecret; return "Basic " + Base64.encodeBase64String(str.getBytes()); }
/** * 获取美国店铺的token * * @return */ private String getUSAAccessToken(String clientId, String clientSecret, String accountName, String tokenUrl) { String accessToken; String authorization = getAuthorization(clientId, clientSecret); Map<String, String> headers = new HashMap<>(); headers.put("Authorization", authorization); headers.put("WM_SVC.NAME", accountName); headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString()); try { HttpResponse response = HttpRequest.post(tokenUrl) .addHeaders(headers) .body("grant_type=client_credentials", "application/x-www-form-urlencoded") .execute(); JSONObject jsonObject = JSONObject.parseObject(response.body()); accessToken = jsonObject.getString("access_token"); if (accessToken == null) { System.out.println("获取沃尔玛接口调用凭证失败"); } } catch (Exception e) { System.out.println("请求异常"); return null; } return accessToken; }
/** * 获取所有的刚下单未接单的订单 */ @RequestMapping("/getOrdersCreated") @Transactional public ResultData getOrdersCreated() throws URISyntaxException { //获取授权token String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl); //设置请求头 Map<String, String> headers = new HashMap<>(); headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken); headers.put("WM_SVC.NAME", accountName); headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString()); headers.put("Accept", "application/json"); // 获取数据库中沃尔玛平台的时间 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //设置参数 HashMap<String, Object> objectObjectHashMap = new HashMap<>(); OrderApi orderApi1 = new OrderApi(); orderApi1.setPlatform("Walmart"); List<OrderApi> orders = orderApiMapper.query(orderApi1); Date date1 = orderApiMapper.orderMaxDate(orderApi1); if (null != date1) { String createdStartDate = simpleDateFormat.format(date1); objectObjectHashMap.put("createdStartDate", createdStartDate); } // objectObjectHashMap.put("status", "Created"); objectObjectHashMap.put("limit", "200"); String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpGet, "https://marketplace.walmartapis.com/v3/orders", objectObjectHashMap, headers); JSONObject resultObject = JSONObject.parseObject(response); Map map = (Map) resultObject.get("list"); Map elements = (Map) map.get("elements"); List<Map<String, Object>> orderList = (List<Map<String, Object>>) elements.get("order"); List<OrderApi> orderApiList = new ArrayList<>(); List<OrderDetailApi> orderDetailApiList = new ArrayList<>(); if (!CollectionUtils.isEmpty(orderList)) { Date date = new Date(); String userCode = UserUtils.getUserCode(); for (Map<String, Object> order : orderList) { OrderApi orderApi = new OrderApi(); String purchaseOrderId = (String) order.get("purchaseOrderId"); Optional<OrderApi> first = orders.stream().filter(he -> he.getPo().equals(purchaseOrderId)).findFirst(); if (first.isPresent()) { continue; } String customerOrderId = (String) order.get("customerOrderId"); String customerEmailId = (String) order.get("customerEmailId"); long orderDateLong = (long) order.get("orderDate"); Map shippingInfo = (Map) order.get("shippingInfo"); String phone = (String) shippingInfo.get("phone"); long estimatedDeliveryDateLong = (long) shippingInfo.get("estimatedDeliveryDate"); long estimatedShipDateLong = (long) shippingInfo.get("estimatedShipDate"); String methodCode = (String) shippingInfo.get("methodCode"); Map postalAddress = (Map) shippingInfo.get("postalAddress"); String name = (String) postalAddress.get("name"); String address1 = (String) postalAddress.get("address1"); String address2 = (String) postalAddress.get("address2"); String city = (String) postalAddress.get("city"); String state = (String) postalAddress.get("state"); String postalCode = (String) postalAddress.get("postalCode"); String country = (String) postalAddress.get("country"); Map orderLines = (Map) order.get("orderLines"); orderApi.setPo(purchaseOrderId); orderApi.setPlatform("Walmart"); Date orderDate = new Date(orderDateLong); orderApi.setPoDate(orderDate); orderApi.setShipToPhone(phone); Date estimatedDeliveryDate = new Date(estimatedDeliveryDateLong); orderApi.setMustShipBy(estimatedDeliveryDate); orderApi.setShipMethod(methodCode); orderApi.setShipToName(name); orderApi.setShipToAddressOne(address1); orderApi.setShipToAddressTwo(address2); orderApi.setShipToCity(city); orderApi.setShipToState(state); orderApi.setShipToCountry(country); orderApi.setShipToZip(postalCode); orderApi.setCreateTime(date); orderApi.setCreateUser(userCode); orderApi.setIsHistory("0"); orderApi.setIsOperation("0"); List<Map<String, Object>> orderLine = (List<Map<String, Object>>) orderLines.get("orderLine"); if (!CollectionUtils.isEmpty(orderLine)) { // List<OrderDetailApi> orderDetailApis = new ArrayList<>(); // List<String> skus = new ArrayList<>(); for (Map<String, Object> line : orderLine) { OrderDetailApi orderDetailApi = new OrderDetailApi(); orderDetailApi.setCreateTime(date); orderDetailApi.setCreateUser(userCode); orderDetailApi.setPo(purchaseOrderId); orderDetailApi.setIsHistory("0"); String rowNum = (String) line.get("lineNumber"); Map item = (Map) line.get("item"); String sku = (String) item.get("sku"); String productName = (String) item.get("productName"); // if (!skus.contains(sku)) { // skus.add(sku); // } Map charges = (Map) line.get("charges"); orderDetailApi.setRowNum(rowNum); orderDetailApi.setSku(sku); List<Map<String, Object>> charge = (List<Map<String, Object>>) charges.get("charge"); if (!CollectionUtils.isEmpty(charge)) { Map<String, Object> itemPrice = charge.get(0); Map chargeAmount = (Map) itemPrice.get("chargeAmount"); BigDecimal price = (BigDecimal) chargeAmount.get("amount"); double v = price.doubleValue(); orderDetailApi.setPrice(v); } Map orderLineQuantity = (Map) line.get("orderLineQuantity"); String quantity = (String) orderLineQuantity.get("amount"); int qty = Integer.parseInt(quantity); Map fulfillment = (Map) line.get("fulfillment"); String vendor = (String) fulfillment.get("fulfillmentOption"); Map orderLineStatuses = (Map) line.get("orderLineStatuses"); List<Map<String, Object>> orderLineStatus = (List<Map<String, Object>>) orderLineStatuses.get("orderLineStatus"); if (!CollectionUtils.isEmpty(orderLineStatus)) { Map<String, Object> itemPrice = orderLineStatus.get(0); String status = (String) itemPrice.get("status"); orderApi.setStatus(status); orderDetailApi.setStatus(status); if (status.equals("Created")) { orderApi.setIsOperation("0"); } else { orderApi.setIsOperation("1"); } } orderDetailApi.setVendor(vendor); orderDetailApi.setPoQty(qty); // orderDetailApis.add(orderDetailApi); orderDetailApiList.add(orderDetailApi); } // for (String sku : skus) { // List<OrderDetailApi> collect = orderDetailApis.stream().filter(he -> he.getSku().equals(sku)).collect(Collectors.toList()); // if (!CollectionUtils.isEmpty(collect)) { // OrderDetailApi orderDetailApi = collect.get(0); // int sum = collect.stream().mapToInt(OrderDetailApi::getPoQty).sum(); // orderDetailApi.setPoQty(sum); // 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("/getOrdersAll") @Transactional public ResultData getOrdersAll() throws URISyntaxException { //获取授权token String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl); //设置请求头 Map<String, String> headers = new HashMap<>(); headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken); headers.put("WM_SVC.NAME", accountName); headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString()); headers.put("Accept", "application/json"); OrderApi orderApi1 = new OrderApi(); orderApi1.setPlatform("Walmart"); List<OrderApi> orders = orderApiMapper.query(orderApi1); // 获取数据库中沃尔玛平台的时间 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //半年前 Calendar instance = Calendar.getInstance(); instance.setTime(new Date()); instance.add(Calendar.MONTH, -6); Date time = instance.getTime(); String createdStartDate = simpleDateFormat.format(time); // 设置参数 HashMap<String, Object> objectObjectHashMap = new HashMap<>(); // objectObjectHashMap.put("status","Created"); objectObjectHashMap.put("createdStartDate", createdStartDate); objectObjectHashMap.put("limit", "200"); String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpGet, "https://marketplace.walmartapis.com/v3/orders", objectObjectHashMap, headers); JSONObject resultObject = JSONObject.parseObject(response); Map map = (Map) resultObject.get("list"); Map elements = (Map) map.get("elements"); List<Map<String, Object>> orderList = (List<Map<String, Object>>) elements.get("order"); List<OrderApi> orderApiList = new ArrayList<>(); List<OrderDetailApi> orderDetailApiList = new ArrayList<>(); if (!CollectionUtils.isEmpty(orderList)) { Date date = new Date(); String userCode = UserUtils.getUserCode(); for (Map<String, Object> order : orderList) { OrderApi orderApi = new OrderApi(); //采购单号 String purchaseOrderId = (String) order.get("purchaseOrderId"); //订单号 String customerOrderId = (String) order.get("customerOrderId"); Optional<OrderApi> first = orders.stream().filter(he -> he.getPo().equals(purchaseOrderId)).findFirst(); if (first.isPresent()) { continue; } String customerEmailId = (String) order.get("customerEmailId"); long orderDateLong = (long) order.get("orderDate"); Map shippingInfo = (Map) order.get("shippingInfo"); String phone = (String) shippingInfo.get("phone"); long estimatedDeliveryDateLong = (long) shippingInfo.get("estimatedDeliveryDate"); long estimatedShipDateLong = (long) shippingInfo.get("estimatedShipDate"); String methodCode = (String) shippingInfo.get("methodCode"); Map postalAddress = (Map) shippingInfo.get("postalAddress"); String name = (String) postalAddress.get("name"); String address1 = (String) postalAddress.get("address1"); String address2 = (String) postalAddress.get("address2"); String city = (String) postalAddress.get("city"); String state = (String) postalAddress.get("state"); String postalCode = (String) postalAddress.get("postalCode"); String country = (String) postalAddress.get("country"); Map orderLines = (Map) order.get("orderLines"); orderApi.setPo(purchaseOrderId); orderApi.setPlatform("Walmart"); Date orderDate = new Date(orderDateLong); orderApi.setPoDate(orderDate); orderApi.setShipToPhone(phone); Date estimatedDeliveryDate = new Date(estimatedDeliveryDateLong); orderApi.setMustShipBy(estimatedDeliveryDate); orderApi.setShipMethod(methodCode); orderApi.setShipToName(name); orderApi.setShipToAddressOne(address1); orderApi.setShipToAddressTwo(address2); orderApi.setShipToCity(city); orderApi.setShipToState(state); orderApi.setShipToCountry(country); orderApi.setShipToZip(postalCode); orderApi.setCreateTime(date); orderApi.setCreateUser(userCode); orderApi.setIsHistory("0"); orderApi.setIsOperation("0"); List<Map<String, Object>> orderLine = (List<Map<String, Object>>) orderLines.get("orderLine"); if (!CollectionUtils.isEmpty(orderLine)) { // List<OrderDetailApi> orderDetailApis = new ArrayList<>(); // List<String> skus = new ArrayList<>(); for (Map<String, Object> line : orderLine) { OrderDetailApi orderDetailApi = new OrderDetailApi(); orderDetailApi.setCreateTime(date); orderDetailApi.setCreateUser(userCode); orderDetailApi.setPo(purchaseOrderId); orderDetailApi.setIsHistory("0"); String rowNum = (String) line.get("lineNumber"); Map item = (Map) line.get("item"); String sku = (String) item.get("sku"); String productName = (String) item.get("productName"); // if (!skus.contains(sku)) { // skus.add(sku); // } Map charges = (Map) line.get("charges"); orderDetailApi.setRowNum(rowNum); orderDetailApi.setSku(sku); List<Map<String, Object>> charge = (List<Map<String, Object>>) charges.get("charge"); if (!CollectionUtils.isEmpty(charge)) { Map<String, Object> itemPrice = charge.get(0); Map chargeAmount = (Map) itemPrice.get("chargeAmount"); BigDecimal price = (BigDecimal) chargeAmount.get("amount"); double v = price.doubleValue(); orderDetailApi.setPrice(v); } Map orderLineQuantity = (Map) line.get("orderLineQuantity"); String quantity = (String) orderLineQuantity.get("amount"); int qty = Integer.parseInt(quantity); Map fulfillment = (Map) line.get("fulfillment"); String vendor = (String) fulfillment.get("fulfillmentOption"); Map orderLineStatuses = (Map) line.get("orderLineStatuses"); List<Map<String, Object>> orderLineStatus = (List<Map<String, Object>>) orderLineStatuses.get("orderLineStatus"); if (!CollectionUtils.isEmpty(orderLineStatus)) { Map<String, Object> itemPrice = orderLineStatus.get(0); String status = (String) itemPrice.get("status"); orderApi.setStatus(status); orderDetailApi.setStatus(status); if (status.equals("Created")) { orderApi.setIsOperation("0"); } else { orderApi.setIsOperation("1"); } } orderDetailApi.setVendor(vendor); orderDetailApi.setPoQty(qty); // orderDetailApis.add(orderDetailApi); orderDetailApiList.add(orderDetailApi); } // for (String sku : skus) { // List<OrderDetailApi> collect = orderDetailApis.stream().filter(he -> he.getSku().equals(sku)).collect(Collectors.toList()); // if (!CollectionUtils.isEmpty(collect)) { // OrderDetailApi orderDetailApi = collect.get(0); // int sum = collect.stream().mapToInt(OrderDetailApi::getPoQty).sum(); // orderDetailApi.setPoQty(sum); // 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) throws URISyntaxException { //获取授权token // String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl); String usaAccessToken = getUSAAccessToken(sandboxClientId, sandboxClientSecret, accountName, sandboxTokenUrl); //设置请求头 Map<String, String> headers = new HashMap<>(); headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken); headers.put("WM_SVC.NAME", accountName); headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString()); headers.put("Accept", "application/json"); // 设置参数 String purchaseOrderId = orderApi.getPo(); if (null == purchaseOrderId || StringUtils.isBlank(purchaseOrderId)) { 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 detailApi = new OrderDetailApi(); detailApi.setPo(purchaseOrderId); List<OrderDetailApi> orderDetailApiList = orderDetailApiMapper.query(detailApi); if (CollectionUtils.isEmpty(orderDetailApiList)) { return ResultData.fail("系统没有查到有关于这个" + purchaseOrderId + "的明细信息"); } String status = orderApi1.getStatus(); String url = "https://sandbox.walmartapis.com/v3/orders/" + purchaseOrderId + "/acknowledge"; // String url = "https://walmartapis.com/v3/orders/" + purchaseOrderId + "/acknowledge"; if (status.equals("Created")) { HashMap<String, Object> objectObjectHashMap = new HashMap<>(); String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpPost, url, objectObjectHashMap, headers); JSONObject resultObject = JSONObject.parseObject(response); if (null != resultObject) { List<Map<String, Object>> order = (List<Map<String, Object>>) resultObject.get("order"); if (order.size() == 0) { return ResultData.fail(purchaseOrderId + "接单失败" + "返回错误结果" + response); } Map<String, Object> map = order.get(0); String apiReturnPurchaseOrderId = (String) map.get("purchaseOrderId"); if (purchaseOrderId.equals(apiReturnPurchaseOrderId)) { 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 detail : orderDetailApiList) { 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(detail.getSku()); outboundDetail.setPrice(detail.getPrice()); outboundDetail.setWarehouse("WH231215001"); outboundDetail.setOutQty(0); outboundDetail.setDifferenceQty(0); outboundDetail.setPoQty(1); outboundDetail.setVendor(detail.getVendor()); outboundDetail.setRemark(detail.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.createWalmartOrder(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()); } } else { return ResultData.fail("接单的订单号" + purchaseOrderId + "跟接单请求返回的订单号" + apiReturnPurchaseOrderId + "不一样"); } } else { return ResultData.fail(purchaseOrderId + "接单请求返回数据为空"); } } else { if (status.equals("Cancelled")) { return ResultData.fail(purchaseOrderId + "订单已被取消"); } if (status.equals("Acknowledged")) { return ResultData.fail(purchaseOrderId + "订单已经接单,无需重复接单"); } } return ResultData.succeed(purchaseOrderId + "接单成功"); }
/** * 取消订单 */ @RequestMapping("/cancel") @Transactional public ResultData cancel(OrderApi orderApi) throws URISyntaxException { //获取授权token // String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl); String usaAccessToken = getUSAAccessToken(sandboxClientId, sandboxClientSecret, accountName, sandboxTokenUrl); //设置请求头 Map<String, String> headers = new HashMap<>(); headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken); headers.put("WM_SVC.NAME", accountName); headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString()); headers.put("Accept", "application/json"); // 设置参数 String purchaseOrderId = orderApi.getPo(); 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 + "的信息"); } OrderDetailApi detailApi1 = new OrderDetailApi(); detailApi1.setPo(purchaseOrderId); List<OrderDetailApi> detailApiList = orderDetailApiMapper.query(detailApi1); if (CollectionUtils.isEmpty(detailApiList)) { return ResultData.fail("请传入要取消的要取消的明细数据"); } OrderApi orderApi1 = orders.get(0); String status = orderApi1.getStatus(); String url = "https://sandbox.walmartapis.com/v3/orders/" + purchaseOrderId + "/cancel"; // String url = "https://walmartapis.com/v3/orders/" + purchaseOrderId + "/cancel"; if (status.equals("Created")) { Map<String, Object> objectObjectHashMap = new HashMap<>(); Map<String, Object> orderCancellation = new HashMap<>(); Map<String, Object> orderLines = new HashMap<>(); List<Map<String, Object>> orderLine = new ArrayList<>(); for (OrderDetailApi detailApi : detailApiList) { detailApi.setCancellationReason("SELLER_CANCEL_OUT_OF_STOCK"); Map<String, Object> orderLineItem = new HashMap<>(); orderLineItem.put("lineNumber", detailApi.getRowNum()); Map<String, Object> orderLineStatuses = new HashMap<>(); List<Map<String, Object>> orderLineStatus = new ArrayList<>(); Map<String, Object> orderLineStatusItem = new HashMap<>(); Map<String, Object> statusQuantity = new HashMap<>(); statusQuantity.put("unitOfMeasurement", "EA"); statusQuantity.put("amount", detailApi.getPoQty().toString()); orderLineStatusItem.put("status", "Cancelled"); //取消订单的原因 orderLineStatusItem.put("cancellationReason", detailApi.getCancellationReason()); orderLineStatusItem.put("statusQuantity", statusQuantity); orderLineStatus.add(orderLineStatusItem); orderLineStatuses.put("orderLineStatus", orderLineStatus); orderLineItem.put("orderLineStatuses", orderLineStatuses); orderLine.add(orderLineItem); } orderLines.put("orderLine", orderLine); orderCancellation.put("orderLines", orderLines); objectObjectHashMap.put("orderCancellation", orderCancellation); String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpPost, url, objectObjectHashMap, headers); JSONObject resultObject = JSONObject.parseObject(response); if (null != resultObject) { List<Map<String, Object>> order = (List<Map<String, Object>>) resultObject.get("order"); if (CollectionUtils.isEmpty(order)) { return ResultData.fail(purchaseOrderId + "拒单失败" + "返回错误结果" + response); } Map<String, Object> map = order.get(0); String apiReturnPurchaseOrderId = (String) map.get("purchaseOrderId"); if (purchaseOrderId.equals(apiReturnPurchaseOrderId)) { Date date = new Date(); String userCode = UserUtils.getUserCode(); // OrderApi orderApi2 = new OrderApi(); 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()); } } else { return ResultData.fail("接单的订单号" + purchaseOrderId + "跟接单请求返回的订单号" + apiReturnPurchaseOrderId + "不一样"); } } else { return ResultData.fail(purchaseOrderId + "接单请求返回数据为空"); } } else { if (status.equals("Acknowledged")) { return ResultData.fail(purchaseOrderId + "订单已接单了,无法进行取消"); } if (status.equals("Cancelled")) { return ResultData.fail(purchaseOrderId + "订单已取消,无需重复取消"); } } return ResultData.succeed(purchaseOrderId + "取消订单成功"); }
/** * 获取全部退货单 */ @RequestMapping("/getReturnAll") @Transactional public ResultData getReturnAll() throws URISyntaxException, ParseException { //获取授权token String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl); //设置请求头 Map<String, String> headers = new HashMap<>(); headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken); headers.put("WM_SVC.NAME", accountName); headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString()); headers.put("Accept", "application/json"); ReturnApi returnApi1 = new ReturnApi(); returnApi1.setPlatform("Walmart"); List<ReturnApi> returnApis = returnApiMapper.query(returnApi1); // 获取数据库中沃尔玛平台的时间 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); Date now = new Date(); //半年前 Calendar instance = Calendar.getInstance(); instance.setTime(new Date()); instance.add(Calendar.MONTH, -6); Date time = instance.getTime(); String returnCreationStartDate = simpleDateFormat.format(time); String returnCreationEndDate = simpleDateFormat.format(now); // 设置参数 HashMap<String, Object> objectObjectHashMap = new HashMap<>(); // objectObjectHashMap.put("status","Created"); objectObjectHashMap.put("returnCreationStartDate", returnCreationStartDate); objectObjectHashMap.put("returnCreationEndDate", returnCreationEndDate); objectObjectHashMap.put("limit", "200"); String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpGet, "https://marketplace.walmartapis.com/v3/returns", objectObjectHashMap, headers); JSONObject resultObject = JSONObject.parseObject(response); List<Map<String, Object>> returnOrders = (List<Map<String, Object>>) resultObject.get("returnOrders"); List<ReturnApi> returnApiList = new ArrayList<>(); List<ReturnDetailApi> returnDetailApiList = new ArrayList<>(); if (!CollectionUtils.isEmpty(returnOrders)) { String userCode = UserUtils.getUserCode(); for (Map<String, Object> order : returnOrders) { ReturnApi returnApi = new ReturnApi(); //退货单号 String returnOrderId = (String) order.get("returnOrderId"); Optional<ReturnApi> first1 = returnApis.stream().filter(he -> he.getReturnNum().equals(returnOrderId)).findFirst(); if (first1.isPresent()) { continue; } //客户邮箱地址 String customerEmailId = (String) order.get("customerEmailId"); //客户信息 Map customerName = (Map) order.get("customerName"); String firstName = (String) customerName.get("firstName"); String lastName = (String) customerName.get("lastName"); //客户订单号 String customerOrderId = (String) order.get("customerOrderId"); //退货时间 String orderDateStr = (String) order.get("returnOrderDate"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z"); orderDateStr = orderDateStr.replace("Z", " UTC"); Date orderDate = format.parse(orderDateStr); String returnByDateStr = (String) order.get("returnByDate"); returnByDateStr = returnByDateStr.replace("Z", " UTC"); Date returnByDate = format.parse(returnByDateStr); returnApi.setReturnNum(returnOrderId); returnApi.setIssueDate(orderDate); returnApi.setReturnConfirmationTime(returnByDate); List<Map<String, String>> tackInfos = new ArrayList<>(); List<Map<String, Object>> returnLineGroups = (List<Map<String, Object>>) order.get("returnLineGroups"); if (!CollectionUtils.isEmpty(returnLineGroups)) { Map<String, String> tack = new HashMap<>(); for (Map<String, Object> returnLineGroup : returnLineGroups) { List<Map<String, Object>> returnLines = (List<Map<String, Object>>) returnLineGroup.get("returnLines"); if (!CollectionUtils.isEmpty(returnLines)) { Map<String, Object> map = returnLines.get(0); Integer returnOrderLineNumber = (Integer) map.get("returnOrderLineNumber"); tack.put("returnOrderLineNumber", returnOrderLineNumber.toString()); } List<Map<String, Object>> labels = (List<Map<String, Object>>) returnLineGroup.get("labels"); if (!CollectionUtils.isEmpty(labels)) { Map<String, Object> map = labels.get(0); List<Map<String, Object>> carrierInfoList = (List<Map<String, Object>>) map.get("carrierInfoList"); if (!CollectionUtils.isEmpty(carrierInfoList)) { Map<String, Object> carrierInfo = carrierInfoList.get(0); String carrierName = (String) carrierInfo.get("carrierName"); String trackingNo = (String) carrierInfo.get("trackingNo"); tack.put("carrierName", carrierName); tack.put("trackingNo", trackingNo); } } } tackInfos.add(tack); } List<Map<String, Object>> returnOrderLines = (List<Map<String, Object>>) order.get("returnOrderLines"); if (!CollectionUtils.isEmpty(returnOrderLines)) { for (Map<String, Object> returnOrderLine : returnOrderLines) { //退料行号 Integer returnOrderLineNumber = (Integer) returnOrderLine.get("returnOrderLineNumber"); //采购单号行号 Integer rowNum = (Integer) returnOrderLine.get("purchaseOrderLineNumber"); //采购单号 String purchaseOrderId = (String) returnOrderLine.get("purchaseOrderId"); //退货原因 String returnReason = (String) returnOrderLine.get("returnReason"); Map item = (Map) returnOrderLine.get("item"); //sku String sku = (String) item.get("sku"); Map unitPrice = (Map) returnOrderLine.get("unitPrice"); //价格 BigDecimal currencyAmount = (BigDecimal) unitPrice.get("currencyAmount"); double price = currencyAmount.doubleValue(); Map quantity = (Map) returnOrderLine.get("quantity"); BigDecimal measurementValue = (BigDecimal) quantity.get("measurementValue"); //数量 int qty = measurementValue.intValue(); //状态 String status = (String) returnOrderLine.get("status"); ReturnDetailApi returnDetailApi = new ReturnDetailApi(); returnDetailApi.setReturnNum(returnOrderId); returnDetailApi.setSku(sku); returnDetailApi.setStatus(status); returnDetailApi.setQty(qty); returnDetailApi.setReturnReason(returnReason); returnDetailApi.setRowNum(returnOrderLineNumber.toString()); Optional<Map<String, String>> first = tackInfos.stream().filter(he -> he.get("returnOrderLineNumber").equals(returnOrderLineNumber.toString())).findFirst(); if (first.isPresent()) { Map<String, String> track = first.get(); String carrierName = track.get("carrierName"); String trackingNo = track.get("trackingNo"); returnDetailApi.setCarrier(carrierName); returnDetailApi.setTrackingNum(trackingNo); } returnDetailApi.setCreateTime(now); returnDetailApi.setCreateUser(userCode); returnDetailApi.setIsHistory("0"); returnDetailApiList.add(returnDetailApi); returnApi.setPo(purchaseOrderId); returnApi.setStatus(status); returnApi.setReturnReason(returnReason); } } returnApi.setPlatform("Walmart"); returnApi.setCreateTime(now); returnApi.setCreateUser(userCode); returnApi.setIsHistory("0"); returnApi.setIsOperation("0"); returnApiList.add(returnApi); } } try { if (!CollectionUtils.isEmpty(returnApiList)) { returnApiMapper.insertBatch(returnApiList); } if (!CollectionUtils.isEmpty(returnDetailApiList)) { returnDetailApiMapper.insertBatch(returnDetailApiList); } } catch (Exception exception) { exception.getMessage(); exception.printStackTrace(); System.out.println(exception.getMessage()); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return ResultData.fail("获取异常" + exception.getMessage()); } return ResultData.succeed("api获取数据成功总共" + returnApiList.size() + "个订单"); }
/** * 获取同步退货单 */ @RequestMapping("/getReturnNew") @Transactional public ResultData getReturnNew() throws URISyntaxException, ParseException { //获取授权token String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl); //设置请求头 Map<String, String> headers = new HashMap<>(); headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken); headers.put("WM_SVC.NAME", accountName); headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString()); headers.put("Accept", "application/json"); ReturnApi returnApi1 = new ReturnApi(); returnApi1.setPlatform("Walmart"); List<ReturnApi> returnApis = returnApiMapper.query(returnApi1); Date date = returnApiMapper.orderMaxDate(returnApi1); // 设置参数 HashMap<String, Object> objectObjectHashMap = new HashMap<>(); // 获取数据库中沃尔玛平台的时间 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); Date now = new Date(); if (null != date) { String returnCreationStartDate = simpleDateFormat.format(date); String returnCreationEndDate = simpleDateFormat.format(now); objectObjectHashMap.put("returnCreationStartDate", returnCreationStartDate); objectObjectHashMap.put("returnCreationEndDate", returnCreationEndDate); } //status INITIATED, DELIVERED, COMPLETED // objectObjectHashMap.put("status","INITIATED"); objectObjectHashMap.put("limit", "200"); String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpGet, "https://marketplace.walmartapis.com/v3/returns", objectObjectHashMap, headers); JSONObject resultObject = JSONObject.parseObject(response); List<Map<String, Object>> returnOrders = (List<Map<String, Object>>) resultObject.get("returnOrders"); List<ReturnApi> returnApiList = new ArrayList<>(); List<ReturnDetailApi> returnDetailApiList = new ArrayList<>(); if (!CollectionUtils.isEmpty(returnOrders)) { String userCode = UserUtils.getUserCode(); for (Map<String, Object> order : returnOrders) { ReturnApi returnApi = new ReturnApi(); //退货单号 String returnOrderId = (String) order.get("returnOrderId"); Optional<ReturnApi> first1 = returnApis.stream().filter(he -> he.getReturnNum().equals(returnOrderId)).findFirst(); if (first1.isPresent()) { continue; } //客户邮箱地址 String customerEmailId = (String) order.get("customerEmailId"); //客户信息 Map customerName = (Map) order.get("customerName"); String firstName = (String) customerName.get("firstName"); String lastName = (String) customerName.get("lastName"); //客户订单号 String customerOrderId = (String) order.get("customerOrderId"); //退货时间 String orderDateStr = (String) order.get("returnOrderDate"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z"); orderDateStr = orderDateStr.replace("Z", " UTC"); Date orderDate = format.parse(orderDateStr); String returnByDateStr = (String) order.get("returnByDate"); returnByDateStr = returnByDateStr.replace("Z", " UTC"); Date returnByDate = format.parse(returnByDateStr); returnApi.setReturnNum(returnOrderId); returnApi.setIssueDate(orderDate); returnApi.setReturnConfirmationTime(returnByDate); List<Map<String, String>> tackInfos = new ArrayList<>(); List<Map<String, Object>> returnLineGroups = (List<Map<String, Object>>) order.get("returnLineGroups"); if (!CollectionUtils.isEmpty(returnLineGroups)) { Map<String, String> tack = new HashMap<>(); for (Map<String, Object> returnLineGroup : returnLineGroups) { List<Map<String, Object>> returnLines = (List<Map<String, Object>>) returnLineGroup.get("returnLines"); if (!CollectionUtils.isEmpty(returnLines)) { Map<String, Object> map = returnLines.get(0); Integer returnOrderLineNumber = (Integer) map.get("returnOrderLineNumber"); tack.put("returnOrderLineNumber", returnOrderLineNumber.toString()); } List<Map<String, Object>> labels = (List<Map<String, Object>>) returnLineGroup.get("labels"); if (!CollectionUtils.isEmpty(labels)) { Map<String, Object> map = labels.get(0); List<Map<String, Object>> carrierInfoList = (List<Map<String, Object>>) map.get("carrierInfoList"); if (!CollectionUtils.isEmpty(carrierInfoList)) { Map<String, Object> carrierInfo = carrierInfoList.get(0); String carrierName = (String) carrierInfo.get("carrierName"); String trackingNo = (String) carrierInfo.get("trackingNo"); tack.put("carrierName", carrierName); tack.put("trackingNo", trackingNo); } } } tackInfos.add(tack); } List<Map<String, Object>> returnOrderLines = (List<Map<String, Object>>) order.get("returnOrderLines"); if (!CollectionUtils.isEmpty(returnOrderLines)) { for (Map<String, Object> returnOrderLine : returnOrderLines) { //退料行号 Integer returnOrderLineNumber = (Integer) returnOrderLine.get("returnOrderLineNumber"); //采购单号行号 Integer rowNum = (Integer) returnOrderLine.get("purchaseOrderLineNumber"); //采购单号 String purchaseOrderId = (String) returnOrderLine.get("purchaseOrderId"); //退货原因 String returnReason = (String) returnOrderLine.get("returnReason"); Map item = (Map) returnOrderLine.get("item"); //sku String sku = (String) item.get("sku"); Map unitPrice = (Map) returnOrderLine.get("unitPrice"); //价格 BigDecimal currencyAmount = (BigDecimal) unitPrice.get("currencyAmount"); double price = currencyAmount.doubleValue(); Map quantity = (Map) returnOrderLine.get("quantity"); BigDecimal measurementValue = (BigDecimal) quantity.get("measurementValue"); //数量 int qty = measurementValue.intValue(); //状态 String status = (String) returnOrderLine.get("status"); ReturnDetailApi returnDetailApi = new ReturnDetailApi(); returnDetailApi.setReturnNum(returnOrderId); returnDetailApi.setSku(sku); returnDetailApi.setStatus(status); returnDetailApi.setQty(qty); returnDetailApi.setReturnReason(returnReason); returnDetailApi.setRowNum(returnOrderLineNumber.toString()); Optional<Map<String, String>> first = tackInfos.stream().filter(he -> he.get("returnOrderLineNumber").equals(returnOrderLineNumber.toString())).findFirst(); if (first.isPresent()) { Map<String, String> track = first.get(); String carrierName = track.get("carrierName"); String trackingNo = track.get("trackingNo"); returnDetailApi.setCarrier(carrierName); returnDetailApi.setTrackingNum(trackingNo); } returnDetailApi.setCreateTime(now); returnDetailApi.setCreateUser(userCode); returnDetailApi.setIsHistory("0"); returnDetailApiList.add(returnDetailApi); returnApi.setPo(purchaseOrderId); returnApi.setStatus(status); returnApi.setReturnReason(returnReason); } } returnApi.setPlatform("Walmart"); returnApi.setCreateTime(now); returnApi.setCreateUser(userCode); returnApi.setIsHistory("0"); returnApi.setIsOperation("0"); returnApiList.add(returnApi); } } try { if (!CollectionUtils.isEmpty(returnApiList)) { returnApiMapper.insertBatch(returnApiList); } if (!CollectionUtils.isEmpty(returnDetailApiList)) { returnDetailApiMapper.insertBatch(returnDetailApiList); } } catch (Exception exception) { exception.getMessage(); exception.printStackTrace(); System.out.println(exception.getMessage()); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return ResultData.fail("获取异常" + exception.getMessage()); } return ResultData.succeed("api获取数据成功总共" + returnApiList.size() + "个订单"); }
/** * 库存同步 */ @RequestMapping("/feeds") @Transactional public ResultData feeds(MultipartFile file) throws URISyntaxException { //获取授权token String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl); //设置请求头 Map<String, String> headers = new HashMap<>(); headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken); headers.put("WM_SVC.NAME", accountName); headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString()); headers.put("Accept", "application/json"); //设置参数 HashMap<String, Object> objectObjectHashMap = new HashMap<>(); objectObjectHashMap.put("file", file); String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpPost, "https://sandbox.walmartapis.com/v3/feeds?feedType=inventory", objectObjectHashMap, headers); JSONObject resultObject = JSONObject.parseObject(response); if (null == resultObject.get("feedId")) { return ResultData.fail("批量更新库存出现异常" + response); } return ResultData.succeed("库存批量更新成功"); } }
|