3>远程调用库存服务来批量查询所有商品的库存是否有货
/** * 查询sku是否有库存(商品服务的saveSpuInfoImpl中up方法要用到的,去结算确认页时批量查询有货没也要用到) * @return */ @PostMapping("/hasstock") public R getSkusHasStock(@RequestBody List<Long> skuIds){ List<SkuHasStockVo> vos = wareSkuService.getSkusHasStock(skuIds); return R.ok().setData(vos); } //查询sku是否有库存(saveSpuInfo中up方法要用到的) @Override public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) { List<SkuHasStockVo> skuHasStockVos = skuIds.stream().map(skuId -> { SkuHasStockVo vo = new SkuHasStockVo(); //查询当前sku的总库存量 Long count = baseMapper.getSkuStock(skuId); vo.setSkuId(skuId); vo.setHasStock(count==null?false:true); return vo; }).collect(Collectors.toList()); return skuHasStockVos; } <!-- 查询当前sku的总库存量--> <select id="getSkuStock" resultType="java.lang.Long"> SELECT SUM(stock - stock_locked) FROM wms_ware_sku WHERE sku_id = #{skuId} </select>
package com.saodai.saodaimall.ware.vo; import lombok.Data; /** *查询sku是否有库存的封装类 **/ @Data public class SkuHasStockVo { private Long skuId; //有没有库存 private Boolean hasStock; }
5、订单确认页面的渲染
(1)收货人信息渲染
<p class="p1">填写并核对订单信息 <span style="color: red" th:if="${msg}!=null" > <b>提交订单失败!失败原因是:[[${msg}]]</b></span> </p> <div class="section"> <!--收货人信息--> <div class="top-2"> <span>收货人信息</span> <span>新增收货地址</span> </div> <!--地址--> <div class="top-3 addr-item" th:each="addr:${confirmOrderData.memberAddressVos}"> <p th:attr="def=${addr.defaultStatus},addrId=${addr.id}">[[${addr.name}]]</p><span>[[${addr.name}]] [[${addr.province}]] [[${addr.city}]] [[${addr.region}]] [[${addr.detailAddress}]] [[${addr.phone}]]</span> </div> <p class="p2">更多地址︾</p> <div class="hh1"/> </div>
(2)购物项信息的渲染
1. <!-<!--图片--> <div class="yun1" th:each="item:${confirmOrderData.items}"> <img th:src="${item.image}" class="yun"/> <div class="mi"> <p>[[${item.title}]]<span style="color: red;" th:text="'¥' + ${#numbers.formatDecimal(item.price,3,2)}"> ¥ 499.00</span> <span> [[${item.count}]] </span> <span> [[${confirmOrderData.stocks[item.skuId]?"有货":"无货"}]]</span> </p> <p><span>[[${item.weight}]]kg</span></p> <p class="tui-1"><img src="/static/order/confirm/img/i_07.png"/>支持7天无理由退货</p> </div> </div>
(3)结算区域的渲染
<div class="xia"> <div class="qian"> <p class="qian_y"> <span>[[${confirmOrderData.count}]]</span> <span>件商品,总商品金额:</span> <span class="rmb">¥[[${#numbers.formatDecimal(confirmOrderData.total, 1, 2)}]]</span> </p> <p class="qian_y"> <span>返现:</span> <span class="rmb"> -¥0.00</span> </p> <p class="qian_y"> <span>运费: </span> <span class="rmb">   ¥<b id="fare"></b></span> </p> <p class="qian_y"> <span>服务费: </span> <span class="rmb">   ¥0.00</span> </p> <p class="qian_y"> <span>退换无忧: </span> <span class="rmb">   ¥0.00</span> </p> </div> <div class="yfze"> <p class="yfze_a"><span class="z">应付总额:</span><span class="hq">¥<b id="payPrice">[[${#numbers.formatDecimal(confirmOrderData.payPrice, 1, 2)}]]</b></span> </p> <p class="yfze_b">寄送至: <span id="receiveAddress"></span> 收货人:<span id="receiver"></span></p> </div> <form action="http://order.saodaimall.com/submitOrder" method="post"> <input id="addrInput" type="hidden" name="addrId" /> <input id="payPriceInput" type="hidden" name="payPrice"> <input name="orderToken" th:value="${confirmOrderData.orderToken}" type="hidden"/> <button class="tijiao" type="submit" >提交订单</button> </form> </div>
6、运费的模拟
(1)直接从confirm.html页面的js代码发的请求去查运费
//查运费 function getFare(addrId) { //给表单回填选择的地址 $("#addrInput").val(addrId); $.get("http://saodaimall.com/api/ware/wareinfo/fare?addrId=" + addrId, function (resp) { console.log(resp); $("#fare").text(resp.data.fare); var total = [[${confirmOrderData.total}]]; var payPrice = total * 1 + resp.data.fare * 1; //设置运费 $("#payPrice").text(payPrice); $("#payPriceInput").val(payPrice); //设置收获地址人信息 $("#receiveAddress").text(resp.data.address.province + " " + resp.data.address.city + " " + " " + resp.data.address.region + resp.data.address.detailAddress); $("#receiver").text(resp.data.address.name); }) }
(2)这个请求由库存服务的WareInfoController控制器来处理
/** * 获取运费信息(订单结算界面时) * @return */ @GetMapping(value = "/fare") public R getFare(@RequestParam("addrId") Long addrId) { FareVo fare = wareInfoService.getFare(addrId); return R.ok().setData(fare); }
分流程:
1、远程调用会员服务的MemberReceiveAddressController控制器来查找用户收货信息MemberAddressVo对象
2、截取用户手机号码最后一位作运费计算
/** * 获取运费信息(订单结算界面时) * @param addrId * @return */ @Override public FareVo getFare(Long addrId) { FareVo fareVo = new FareVo(); //收获地址的详细信息 R addrInfo = memberFeignService.info(addrId); MemberAddressVo memberAddressVo = addrInfo.getData("memberReceiveAddress",new TypeReference<MemberAddressVo>() {}); if (memberAddressVo != null) { String phone = memberAddressVo.getPhone(); //截取用户手机号码最后一位作为我们的运费计算 //1558022051 String fare = phone.substring(phone.length() - 1, phone.length()); BigDecimal bigDecimal = new BigDecimal(fare); fareVo.setFare(bigDecimal); fareVo.setAddress(memberAddressVo); return fareVo; } return null; }
package com.saodai.saodaimall.ware.vo; import lombok.Data; import java.math.BigDecimal; /** *运费vo类 **/ @Data public class FareVo { //用户信息 private MemberAddressVo address; //运费 private BigDecimal fare; }
package com.saodai.saodaimall.ware.vo; import lombok.Data; /** * 会员信息 **/ @Data public class MemberAddressVo { private Long id; /** * member_id */ private Long memberId; /** * 收货人姓名 */ private String name; /** * 电话 */ private String phone; /** * 邮政编码 */ private String postCode; /** * 省份/直辖市 */ private String province; /** * 城市 */ private String city; /** * 区 */ private String region; /** * 详细地址(街道) */ private String detailAddress; /** * 省市区代码 */ private String areacode; /** * 是否默认 */ private Integer defaultStatus; } /** * 根据地址id找到地址信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("member:memberreceiveaddress:info") public R info(@PathVariable("id") Long id){ MemberReceiveAddressEntity memberReceiveAddress = memberReceiveAddressService.getById(id); return R.ok().put("memberReceiveAddress", memberReceiveAddress); }
7、提交订单(点击提交订单按钮,下单)
(1)订单服务的web的OrderWebController控制器来处理/submitOrder请求
/** * 下单功能(提交订单) * @param vo * OrderSubmitVo对象是确认订单页面的部分数据,自动封装好的,因为后面提交订单需要这些数据 * @return */ @PostMapping(value = "/submitOrder") public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes attributes) { //这里进行异常处理是为了防止出错导致系统奔溃,即使出错了也可以保证跳转到提交订单的界面 try { SubmitOrderResponseVo responseVo = orderService.submitOrder(vo); //下单成功来到支付选择页 //下单失败回到订单确认页重新确定订单信息 if (responseVo.getCode() == 0) { //成功 model.addAttribute("submitOrderResp",responseVo); return "pay"; } else { String msg = "下单失败"; switch (responseVo.getCode()) { case 1: msg += "令牌订单信息过期,请刷新再次提交"; break; case 2: msg += "订单商品价格发生变化,请确认后再次提交"; break; case 3: msg += "商品库存不足"; break; } attributes.addFlashAttribute("msg",msg); return "redirect:http://order.saodaimall.com/toTrade"; } } catch (Exception e) { if (e instanceof NoStockException) { String message = ((NoStockException)e).getMessage(); attributes.addFlashAttribute("msg",message); } return "redirect:http://order.saodaimall.com/toTrade"; } }
OrderSubmitVo对象是确认订单页面的部分数据,自动封装好的,因为后面提交订单需要这些数据
package com.saodai.saodaimall.order.vo; import lombok.Data; import java.math.BigDecimal; /** * 封装订单提交数据的vo **/ @Data public class OrderSubmitVo { /** 收获地址的id **/ private Long addrId; /** 支付方式 **/ private Integer payType; //无需提交要购买的商品,去购物车再获取一遍 //优惠、发票 /** 防重令牌 **/ private String orderToken; /** 应付价格 **/ private BigDecimal payPrice; /** 订单备注 **/ private String remarks; //用户相关的信息,直接去session中取出即可 }
(2)OrderServiceImpl的submitOrder方法的具体实现
注意:这个submitOrder方法方法非常复杂,可以从对象的封装来一步步理解
/** * 获取运费信息(订单结算界面时) * @return */ @GetMapping(value = "/fare") public R getFare(@RequestParam("addrId") Long addrId) { FareVo fare = wareInfoService.getFare(addrId); return R.ok().setData(fare); } private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>(); @Autowired private MemberFeignService memberFeignService; @Autowired private CartFeignService cartFeignService; @Autowired private WmsFeignService wmsFeignService; @Autowired private ProductFeignService productFeignService; @Autowired private OrderItemService orderItemService; @Autowired private StringRedisTemplate redisTemplate; @Autowired private RabbitTemplate rabbitTemplate; /** * 创建订单(下单) * // @Transactional(isolation = Isolation.READ_COMMITTED) 设置事务的隔离级别 * // @Transactional(propagation = Propagation.REQUIRED) 设置事务的传播级别 * */ @Transactional(rollbackFor = Exception.class) @Override public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) { //把OrderSubmitVo对象放到本地线程,方便后面共享 confirmVoThreadLocal.set(vo); SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo(); //去创建、下订单、验令牌、验价格、锁定库存... //获取当前用户登录的信息 MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get(); //所在默认状态码为0表示没有异常 responseVo.setCode(0); /**1、验证令牌是否合法【令牌的对比和删除必须保证原子性】**/ String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; String orderToken = vo.getOrderToken(); //通过lure脚本原子验证令牌和删除令牌(执行脚本后返回long类型的0或1,0表示令牌验证失败,1表示成功) //Arrays.asList(USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId())表示存到redis里的值 // orderToken是页面传过来的令牌(表示当前需要验证的值) Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId()), orderToken); if (result == 0L) { //令牌验证失败 responseVo.setCode(1); return responseVo; } else { //令牌验证成功 /**2、创建订单、订单项等信息(抽取成createOrder方法)**/ OrderCreateTo order = createOrder(); //后端计算出的价格 BigDecimal payAmount = order.getOrder().getPayAmount(); //前端界面传来的价格 BigDecimal payPrice = vo.getPayPrice(); //只要这两个的差值小于0.01都是可以接受的 /**3、验证前端界面传来的价格和计算后的价格是否相同(验价)**/ if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) { //金额对比 /**4、保存订单信息**/ saveOrder(order); //4、库存锁定,只要有异常,回滚订单数据 //订单号、所有订单项信息(skuId,skuNum,skuName) WareSkuLockVo lockVo = new WareSkuLockVo(); lockVo.setOrderSn(order.getOrder().getOrderSn()); //获取出要锁定的商品数据信息 List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map((item) -> { OrderItemVo orderItemVo = new OrderItemVo(); orderItemVo.setSkuId(item.getSkuId()); orderItemVo.setCount(item.getSkuQuantity()); orderItemVo.setTitle(item.getSkuName()); return orderItemVo; }).collect(Collectors.toList()); lockVo.setLocks(orderItemVos); //TODO 调用远程锁定库存的方法 //出现的问题:扣减库存成功了,但是由于网络原因超时,出现异常,导致订单事务回滚,库存事务不回滚(解决方案:seata) //为了保证高并发,不推荐使用seata,因为是加锁,并行化,提升不了效率,可以发消息给库存服务 R r = wmsFeignService.orderLockStock(lockVo); if (r.getCode() == 0) { //锁定成功 responseVo.setOrder(order.getOrder()); // int i = 10/0; //这里使用消息队列是用于处理超过指定时间还未支付的订单(也就是把这些订单给取消) /** * 订单创建成功,发送消息给MQ交换机order-event-exchange,交换机根据路由键order.create.order把消息放到延时队列order.delay.queue * 当消息在延时队列里等待了指定的时间后还没有被消费就会再次由交换机路由到队列order.release.order * 这个设置是在MyRabbitMQConfig中指定的 arguments.put("x-dead-letter-routing-key", "order.release.order"); */ rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder()); //删除购物车里的数据 // redisTemplate.delete(CART_PREFIX+memberResponseVo.getId()); return responseVo; } else { //锁定失败 // String msg = (String) r.get("msg"); // throw new NoStockException(msg); /** * Code 1: "令牌订单信息过期,请刷新再次提交"; * Code 2: "订单商品价格发生变化,请确认后再次提交"; * Code 3: "商品库存不足"; */ responseVo.setCode(3); return responseVo; } } else { responseVo.setCode(2); return responseVo; } } } /** * 创建订单 */ private OrderCreateTo createOrder() { OrderCreateTo createTo = new OrderCreateTo(); //1、生成订单号(IdWorker.getTimeId()是jdk提供的生成订单订单号的方法) String orderSn = IdWorker.getTimeId(); //订单构造(将订单构造抽取为builderOrder方法) OrderEntity orderEntity = builderOrder(orderSn); //2、获取到所有的订单项(将所有订单项构造抽取为builderOrderItems方法) List<OrderItemEntity> orderItemEntities = builderOrderItems(orderSn); //3、计算订单各种价格(总价,优惠价,积分价等等) computePrice(orderEntity,orderItemEntities); createTo.setOrder(orderEntity); createTo.setOrderItems(orderItemEntities); return createTo; } /** * 构建订单数据 * @param orderSn 订单号 * @return */ private OrderEntity builderOrder(String orderSn) { /**通过拦截器中线程共享数据来获取当前用户登录信息**/ MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get(); OrderEntity orderEntity = new OrderEntity(); orderEntity.setMemberId(memberResponseVo.getId()); orderEntity.setOrderSn(orderSn); orderEntity.setMemberUsername(memberResponseVo.getUsername()); /**通过线程共享数据来获取地址id信息**/ OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get(); /**通过远程获取收货地址和运费信息来**/ R fareAddressVo = wmsFeignService.getFare(orderSubmitVo.getAddrId()); FareVo fareResp = fareAddressVo.getData("data", new TypeReference<FareVo>() {}); //获取到运费信息 BigDecimal fare = fareResp.getFare(); orderEntity.setFreightAmount(fare); //获取到收货地址信息 MemberAddressVo address = fareResp.getAddress(); //设置收货人信息 orderEntity.setReceiverName(address.getName()); orderEntity.setReceiverPhone(address.getPhone()); //设置收货人邮编 orderEntity.setReceiverPostCode(address.getPostCode()); orderEntity.setReceiverProvince(address.getProvince()); orderEntity.setReceiverCity(address.getCity()); //设置地区 orderEntity.setReceiverRegion(address.getRegion()); //设置详细地址 orderEntity.setReceiverDetailAddress(address.getDetailAddress()); //设置订单相关的状态信息 CREATE_NEW(0,"待付款") orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode()); //设置自动确认时间(天) orderEntity.setAutoConfirmDay(7); //设置确认收货状态[0->未确认;1->已确认] orderEntity.setConfirmStatus(0); return orderEntity; } /** * 构建所有订单项数据 * @param orderSn 订单号 * @return */ public List<OrderItemEntity> builderOrderItems(String orderSn) { List<OrderItemEntity> orderItemEntityList = new ArrayList<>(); //最后确定每个购物项的价格 List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems(); if (currentCartItems != null && currentCartItems.size() > 0) { orderItemEntityList = currentCartItems.stream().map((items) -> { //构建订单项数据 OrderItemEntity orderItemEntity = builderOrderItem(items); orderItemEntity.setOrderSn(orderSn); return orderItemEntity; }).collect(Collectors.toList()); } return orderItemEntityList; } /** * 构建某一个订单项的数据 * @param items 购物项 * @return */ private OrderItemEntity builderOrderItem(OrderItemVo items) { OrderItemEntity orderItemEntity = new OrderItemEntity(); //1、商品的spu信息 Long skuId = items.getSkuId(); /**远程调用商品服务来获取spu的信息**/ R spuInfo = productFeignService.getSpuInfoBySkuId(skuId); SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() { }); orderItemEntity.setSpuId(spuInfoData.getId()); orderItemEntity.setSpuName(spuInfoData.getSpuName()); orderItemEntity.setSpuBrand(spuInfoData.getBrandName()); orderItemEntity.setCategoryId(spuInfoData.getCatalogId()); //2、商品的sku信息 orderItemEntity.setSkuId(skuId); orderItemEntity.setSkuName(items.getTitle()); //设置商品sku图片 orderItemEntity.setSkuPic(items.getImage()); //设置商品sku价格 orderItemEntity.setSkuPrice(items.getPrice()); //商品购买的数量 orderItemEntity.setSkuQuantity(items.getCount()); //使用StringUtils.collectionToDelimitedString将list集合转换为String String skuAttrValues = StringUtils.collectionToDelimitedString(items.getSkuAttrValues(), ";"); //设置商品销售属性组合(JSON) orderItemEntity.setSkuAttrsVals(skuAttrValues); //3、商品的优惠信息 //4、商品的积分信息 //设置赠送成长值 orderItemEntity.setGiftGrowth(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue()); //设置赠送积分 orderItemEntity.setGiftIntegration(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue()); //5、订单项的价格信息 //设置商品促销分解金额 orderItemEntity.setPromotionAmount(BigDecimal.ZERO); //设置优惠券优惠分解金额 orderItemEntity.setCouponAmount(BigDecimal.ZERO); //设置积分优惠分解金额 orderItemEntity.setIntegrationAmount(BigDecimal.ZERO); //当前订单项的实际金额.总额 - 各种优惠价格 //原来的价格 orderItemEntity.getSkuQuantity()是获取商品购买的数量 BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString())); //原价减去优惠价得到最终的价格 BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount()) .subtract(orderItemEntity.getPromotionAmount()) .subtract(orderItemEntity.getIntegrationAmount()); orderItemEntity.setRealAmount(subtract); return orderItemEntity; } /** * 保存订单所有数据 * @param orderCreateTo */ private void saveOrder(OrderCreateTo orderCreateTo) { //获取订单信息 OrderEntity order = orderCreateTo.getOrder(); order.setModifyTime(new Date()); order.setCreateTime(new Date()); //保存订单 this.baseMapper.insert(order); //获取订单项信息 List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems(); //批量保存订单项数据(代码构造器自动生成的方法) orderItemService.saveBatch(orderItems); } /** * 计算价格的方法 */ private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) { //总价 BigDecimal total = new BigDecimal("0.0"); //优惠券优惠分解金额 BigDecimal coupon = new BigDecimal("0.0"); //积分优惠分解金额 BigDecimal intergration = new BigDecimal("0.0"); //商品促销分解金额 BigDecimal promotion = new BigDecimal("0.0"); //积分、成长值 Integer integrationTotal = 0; Integer growthTotal = 0; //订单总额,叠加每一个订单项的总额信息 for (OrderItemEntity orderItem : orderItemEntities) { //优惠券优惠总金额 coupon = coupon.add(orderItem.getCouponAmount()); //商品促销总金额 promotion = promotion.add(orderItem.getPromotionAmount()); //积分优惠总金额 intergration = intergration.add(orderItem.getIntegrationAmount()); //总价 total = total.add(orderItem.getRealAmount()); //赠送总积分 integrationTotal += orderItem.getGiftIntegration(); //赠送总成长值 growthTotal += orderItem.getGiftGrowth(); } //1、订单价格相关的 orderEntity.setTotalAmount(total); //设置应付总额(总额+运费) orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount())); //设置优惠总价 orderEntity.setCouponAmount(coupon); //设置商品促销总价 orderEntity.setPromotionAmount(promotion); //设置积分优惠总价 orderEntity.setIntegrationAmount(intergration); //设置积分 orderEntity.setIntegration(integrationTotal); //设置成长值 orderEntity.setGrowth(growthTotal); //设置订单删除状态(0-未删除,1-已删除) orderEntity.setDeleteStatus(0); }
分流程(submitOrder方法是封装SubmitOrderResponseVo对象):
package com.saodai.saodaimall.order.vo; import com.saodai.saodaimall.order.entity.OrderEntity; import lombok.Data; /** * 下单后返回的数据封装类 **/ @Data public class SubmitOrderResponseVo { //下单成功的订单信息 private OrderEntity order; /** 错误状态码 **/ private Integer code; }
1、把OrderSubmitVo对象(前台传过来已经封装好的)放到本地线程,方便后面共享
package com.saodai.saodaimall.order.vo; import lombok.Data; import java.math.BigDecimal; /** * 封装订单提交数据的vo **/ @Data public class OrderSubmitVo { /** 收获地址的id **/ private Long addrId; /** 支付方式 **/ private Integer payType; //无需提交要购买的商品,去购物车再获取一遍 //优惠、发票 /** 防重令牌 **/ private String orderToken; /** 应付价格 **/ private BigDecimal payPrice; /** 订单备注 **/ private String remarks; //用户相关的信息,直接去session中取出即可 }
2、验证令牌是否合法【令牌的对比和删除必须保证原子性】
3、创建订单(订单和订单项都有对应的数据库表)-->(封装OrderCreateTo对象)
package com.saodai.saodaimall.order.to; import com.saodai.saodaimall.order.entity.OrderEntity; import com.saodai.saodaimall.order.entity.OrderItemEntity; import lombok.Data; import java.math.BigDecimal; import java.util.List; /** *生成的订单类(组合类型的订单) **/ @Data public class OrderCreateTo { //订单实体类 private OrderEntity order; //订单项 private List<OrderItemEntity> orderItems; /** 订单计算的应付价格 **/ private BigDecimal payPrice; /** 运费 **/ private BigDecimal fare; }
i、IdWorker.getTimeId()是jdk提供的生成订单订单号的方法
ii、通过builderOrder方法来构造订单(封装OrderEntity对象)
package com.saodai.saodaimall.order.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; /** * 订单实体类 */ @Data @TableName("oms_order") public class OrderEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId private Long id; /** * member_id */ private Long memberId; /** * 订单号 */ private String orderSn; /** * 使用的优惠券 */ private Long couponId; /** * create_time */ private Date createTime; /** * 用户名 */ private String memberUsername; /** * 订单总额 */ private BigDecimal totalAmount; /** * 应付总额 */ private BigDecimal payAmount; /** * 运费金额 */ private BigDecimal freightAmount; /** * 促销优化金额(促销价、满减、阶梯价) */ private BigDecimal promotionAmount; /** * 积分抵扣金额 */ private BigDecimal integrationAmount; /** * 优惠券抵扣金额 */ private BigDecimal couponAmount; /** * 后台调整订单使用的折扣金额 */ private BigDecimal discountAmount; /** * 支付方式【1->支付宝;2->微信;3->银联; 4->货到付款;】 */ private Integer payType; /** * 订单来源[0->PC订单;1->app订单] */ private Integer sourceType; /** * 订单状态【0->待付款;1->待发货;2->已发货;3->已完成;4->已关闭;5->无效订单】 */ private Integer status; /** * 物流公司(配送方式) */ private String deliveryCompany; /** * 物流单号 */ private String deliverySn; /** * 自动确认时间(天) */ private Integer autoConfirmDay; /** * 可以获得的积分 */ private Integer integration; /** * 可以获得的成长值 */ private Integer growth; /** * 发票类型[0->不开发票;1->电子发票;2->纸质发票] */ private Integer billType; /** * 发票抬头 */ private String billHeader; /** * 发票内容 */ private String billContent; /** * 收票人电话 */ private String billReceiverPhone; /** * 收票人邮箱 */ private String billReceiverEmail; /** * 收货人姓名 */ private String receiverName; /** * 收货人电话 */ private String receiverPhone; /** * 收货人邮编 */ private String receiverPostCode; /** * 省份/直辖市 */ private String receiverProvince; /** * 城市 */ private String receiverCity; /** * 区 */ private String receiverRegion; /** * 详细地址 */ private String receiverDetailAddress; /** * 订单备注 */ private String note; /** * 确认收货状态[0->未确认;1->已确认] */ private Integer confirmStatus; /** * 删除状态【0->未删除;1->已删除】 */ private Integer deleteStatus; /** * 下单时使用的积分 */ private Integer useIntegration; /** * 支付时间 */ private Date paymentTime; /** * 发货时间 */ private Date deliveryTime; /** * 确认收货时间 */ private Date receiveTime; /** * 评价时间 */ private Date commentTime; /** * 修改时间 */ private Date modifyTime; /** * 订单项 */ @TableField(exist = false) private List<OrderItemEntity> orderItemEntityList; } /** * 构建订单数据 * @param orderSn 订单号 * @return */ private OrderEntity builderOrder(String orderSn) { /**通过拦截器中线程共享数据来获取当前用户登录信息**/ MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get(); OrderEntity orderEntity = new OrderEntity(); orderEntity.setMemberId(memberResponseVo.getId()); orderEntity.setOrderSn(orderSn); orderEntity.setMemberUsername(memberResponseVo.getUsername()); /**通过线程共享数据来获取地址id信息**/ OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get(); /**通过远程获取收货地址和运费信息来**/ R fareAddressVo = wmsFeignService.getFare(orderSubmitVo.getAddrId()); FareVo fareResp = fareAddressVo.getData("data", new TypeReference<FareVo>() {}); //获取到运费信息 BigDecimal fare = fareResp.getFare(); orderEntity.setFreightAmount(fare); //获取到收货地址信息 MemberAddressVo address = fareResp.getAddress(); //设置收货人信息 orderEntity.setReceiverName(address.getName()); orderEntity.setReceiverPhone(address.getPhone()); //设置收货人邮编 orderEntity.setReceiverPostCode(address.getPostCode()); orderEntity.setReceiverProvince(address.getProvince()); orderEntity.setReceiverCity(address.getCity()); //设置地区 orderEntity.setReceiverRegion(address.getRegion()); //设置详细地址 orderEntity.setReceiverDetailAddress(address.getDetailAddress()); //设置订单相关的状态信息 CREATE_NEW(0,"待付款") orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode()); //设置自动确认时间(天) orderEntity.setAutoConfirmDay(7); //设置确认收货状态[0->未确认;1->已确认] orderEntity.setConfirmStatus(0); return orderEntity; }
通过拦截器中线程共享数据来获取当前用户登录信息并封装到订单对象 OrderEntity
通过线程共享数据来获取前台提交过来的orderSubmitVo对象数据
通过AddrId地址Id来远程库存服务获取收货地址和运费信息来封装到订单对象OrderEntity
设置订单相关的状态信息为待付款
设置自动确认时间(天)和设置确认收货状态[0->未确认;1->已确认]
iii、通过builderOrderItems方法来构造所有订单项(封装 List<OrderItemEntity>对象,指的所有订单项)
package com.saodai.saodaimall.order.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; /** * 订单项信息 */ @Data @TableName("oms_order_item") public class OrderItemEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId private Long id; /** * order_id */ private Long orderId; /** * order_sn */ private String orderSn; /** * spu_id */ private Long spuId; /** * spu_name */ private String spuName; /** * spu_pic */ private String spuPic; /** * 品牌 */ private String spuBrand; /** * 商品分类id */ private Long categoryId; /** * 商品sku编号 */ private Long skuId; /** * 商品sku名字 */ private String skuName; /** * 商品sku图片 */ private String skuPic; /** * 商品sku价格 */ private BigDecimal skuPrice; /** * 商品购买的数量 */ private Integer skuQuantity; /** * 商品销售属性组合(JSON) */ private String skuAttrsVals; /** * 商品促销分解金额 */ private BigDecimal promotionAmount; /** * 优惠券优惠分解金额 */ private BigDecimal couponAmount; /** * 积分优惠分解金额 */ private BigDecimal integrationAmount; /** * 该商品经过优惠后的分解金额 */ private BigDecimal realAmount; /** * 赠送积分 */ private Integer giftIntegration; /** * 赠送成长值 */ private Integer giftGrowth; } /** * 构建所有订单项数据 * @param orderSn 订单号 * @return */ public List<OrderItemEntity> builderOrderItems(String orderSn) { List<OrderItemEntity> orderItemEntityList = new ArrayList<>(); //获取购物车中选中了的购物项 List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems(); if (currentCartItems != null && currentCartItems.size() > 0) { orderItemEntityList = currentCartItems.stream().map((items) -> { //构建订单项数据 OrderItemEntity orderItemEntity = builderOrderItem(items); orderItemEntity.setOrderSn(orderSn); return orderItemEntity; }).collect(Collectors.toList()); } return orderItemEntityList; } /** * 构建某一个订单项的数据 * @param items 购物项 * @return */ private OrderItemEntity builderOrderItem(OrderItemVo items) { OrderItemEntity orderItemEntity = new OrderItemEntity(); //1、商品的spu信息 Long skuId = items.getSkuId(); /**远程调用商品服务来获取spu的信息**/ R spuInfo = productFeignService.getSpuInfoBySkuId(skuId); SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() { }); orderItemEntity.setSpuId(spuInfoData.getId()); orderItemEntity.setSpuName(spuInfoData.getSpuName()); orderItemEntity.setSpuBrand(spuInfoData.getBrandName()); orderItemEntity.setCategoryId(spuInfoData.getCatalogId()); //2、商品的sku信息 orderItemEntity.setSkuId(skuId); orderItemEntity.setSkuName(items.getTitle()); //设置商品sku图片 orderItemEntity.setSkuPic(items.getImage()); //设置商品sku价格 orderItemEntity.setSkuPrice(items.getPrice()); //商品购买的数量 orderItemEntity.setSkuQuantity(items.getCount()); //使用StringUtils.collectionToDelimitedString将list集合转换为String String skuAttrValues = StringUtils.collectionToDelimitedString(items.getSkuAttrValues(), ";"); //设置商品销售属性组合(JSON) orderItemEntity.setSkuAttrsVals(skuAttrValues); //3、商品的优惠信息 //4、商品的积分信息 //设置赠送成长值 orderItemEntity.setGiftGrowth(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue()); //设置赠送积分 orderItemEntity.setGiftIntegration(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue()); //5、订单项的价格信息 //设置商品促销分解金额 orderItemEntity.setPromotionAmount(BigDecimal.ZERO); //设置优惠券优惠分解金额 orderItemEntity.setCouponAmount(BigDecimal.ZERO); //设置积分优惠分解金额 orderItemEntity.setIntegrationAmount(BigDecimal.ZERO); //当前订单项的实际金额.总额 - 各种优惠价格 //原来的价格 orderItemEntity.getSkuQuantity()是获取商品购买的数量 BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString())); //原价减去优惠价得到最终的价格 BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount()) .subtract(orderItemEntity.getPromotionAmount()) .subtract(orderItemEntity.getIntegrationAmount()); orderItemEntity.setRealAmount(subtract); return orderItemEntity; }