当前位置:   article > 正文

基于springboot的点餐系统微信小程序_基于springboot的微信点餐小程序

基于springboot的微信点餐小程序

随着互联网技术的发展与不断变革,市面上很多奶茶店的点餐方式已经不能满足日益增长的客流量,因此为了解决这一问题,研究设计了一个微信小程序点餐系统。论文首先介绍了微信小程序点餐系统的开发背景和现状,随后阐述了设计该系统的目标,进行了系统的需求分析和开发技术方案设计,较详细的论述了系统的详细设计和实现。

微信小程序点餐系统的开发是基于B/S结构来进行开发的,同时运用当下热门的Spring Boot技术,数据库采用MySQL来作为数据的存储和管理,很大的保障了数据的完整性,也为开发这个系统提供了安全性。

系统根据微信小程序点餐系统调研总结出所需要的开发的各种功能,能够很好的实现数据的增删查改,还对系统的前台小程序端和后台管理这两个模块进行了优化,以满足不同权限下不同用户的实际需求,系统分工明确,能够极大的提高点餐管理信息的效率,本系统界面简洁、易操作、功能较多、安全性高、实用性强,是一个具有良好功能扩展性以及简单维护性的信息管理系统。该系统功能齐全,界面布局比较吸引人,功能比较全,操作简单,符合当今社会的发展趋势。

关键词:点餐系统  B/S结构  Spring Boot  MySQL 

【597】基于springboot的点餐系统微信小程序演示视频

ABSTRACT

With the development and continuous transformation of Internet technology, the  method of placing orders in many milk tea shops on the market has become unable to meet the increasing customer flow. Therefore, in order to solve this problem, a system of Yihetang of City College was designed. The paper firstly introduces the development background and current situation of Yihetang ordering system of the City College,  then elaborates the goal of designing the system, carries on the demand analysis of the system and develops the technical scheme design, and discusses the detailed design and realization of the system in detail.

The development of Yihetang ordering system of City College is based on B/S structure. At the same time, the popular spring boot technology is used, MySQL is used as data storage and management, which greatly guarantees the integrity of data and provides security for the development of this system.

According to the investigation of Yihetang ordering system of City College, the system summarizes all kinds of functions that need to be developed, which can well realize the addition, deletion, check and modification of data. It also optimizes the two modules of the system, the Wechat Mini Program and the background management, so that the system can meet the actual needs of different users under different permissions. The system layout is clear and easy to understand, which speeds up the management of order information. The system has been tested and studied many times, and the results are stable, easy to operate and fast. It is an information management system with many functions, strong security and practicability, various excellent function expansibility and simple maintenance. The system is fully functional, the interface layout is attractive, the function is more complete, the operation is simple, in line with the development trend of today's society

Keywords: Ordering system  B/S structure  Spring Boot  MySQL

  1. package com.qingshop.mall.modules.wxapi.controller;
  2. import java.math.BigDecimal;
  3. import java.sql.Timestamp;
  4. import java.text.SimpleDateFormat;
  5. import java.util.ArrayList;
  6. import java.util.Arrays;
  7. import java.util.Date;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. import java.util.Random;
  12. import java.util.stream.Collectors;
  13. import javax.servlet.http.HttpServletRequest;
  14. import com.qingshop.mall.common.utils.UUIDUtil;
  15. import org.apache.commons.lang3.ObjectUtils;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.transaction.annotation.Transactional;
  20. import org.springframework.web.bind.annotation.GetMapping;
  21. import org.springframework.web.bind.annotation.PostMapping;
  22. import org.springframework.web.bind.annotation.RequestBody;
  23. import org.springframework.web.bind.annotation.RequestMapping;
  24. import org.springframework.web.bind.annotation.RestController;
  25. import com.alibaba.fastjson.JSONObject;
  26. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  27. import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
  28. import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
  29. import com.github.binarywang.wxpay.service.WxPayService;
  30. import com.qingshop.mall.common.bean.Rest;
  31. import com.qingshop.mall.common.utils.IpUtils;
  32. import com.qingshop.mall.common.utils.StringUtils;
  33. import com.qingshop.mall.common.utils.idwork.DistributedIdWorker;
  34. import com.qingshop.mall.common.utils.text.Convert;
  35. import com.qingshop.mall.framework.resolver.LoginUser;
  36. import com.qingshop.mall.modules.common.BaseController;
  37. import com.qingshop.mall.modules.mall.entity.MallAddress;
  38. import com.qingshop.mall.modules.mall.entity.MallCart;
  39. import com.qingshop.mall.modules.mall.entity.MallCoupon;
  40. import com.qingshop.mall.modules.mall.entity.MallCouponUser;
  41. import com.qingshop.mall.modules.mall.entity.MallGoods;
  42. import com.qingshop.mall.modules.mall.entity.MallGoodsSkudetail;
  43. import com.qingshop.mall.modules.mall.entity.MallOrder;
  44. import com.qingshop.mall.modules.mall.entity.MallOrderDetail;
  45. import com.qingshop.mall.modules.mall.entity.MallOrderSerial;
  46. import com.qingshop.mall.modules.mall.entity.MallRegion;
  47. import com.qingshop.mall.modules.mall.entity.MallSaleArea;
  48. import com.qingshop.mall.modules.mall.entity.MallShipFree;
  49. import com.qingshop.mall.modules.mall.entity.MallShipRule;
  50. import com.qingshop.mall.modules.mall.entity.MallShipSet;
  51. import com.qingshop.mall.modules.mall.entity.MallUser;
  52. import com.qingshop.mall.modules.mall.service.IMallAddressService;
  53. import com.qingshop.mall.modules.mall.service.IMallCartService;
  54. import com.qingshop.mall.modules.mall.service.IMallCouponService;
  55. import com.qingshop.mall.modules.mall.service.IMallCouponUserService;
  56. import com.qingshop.mall.modules.mall.service.IMallGoodsService;
  57. import com.qingshop.mall.modules.mall.service.IMallGoodsSkudetailService;
  58. import com.qingshop.mall.modules.mall.service.IMallOrderDetailService;
  59. import com.qingshop.mall.modules.mall.service.IMallOrderSerialService;
  60. import com.qingshop.mall.modules.mall.service.IMallOrderService;
  61. import com.qingshop.mall.modules.mall.service.IMallRegionService;
  62. import com.qingshop.mall.modules.mall.service.IMallSaleAreaService;
  63. import com.qingshop.mall.modules.mall.service.IMallShipFreeService;
  64. import com.qingshop.mall.modules.mall.service.IMallShipRuleService;
  65. import com.qingshop.mall.modules.mall.service.IMallShipSetService;
  66. import com.qingshop.mall.modules.mall.service.IMallUserService;
  67. import io.swagger.annotations.ApiOperation;
  68. @RestController
  69. @RequestMapping("/wx/order")
  70. public class WxOrderController extends BaseController {
  71. private static final Logger log = LoggerFactory.getLogger(WxOrderController.class);
  72. @Autowired
  73. private IMallGoodsService mallGoodService;
  74. @Autowired
  75. private IMallGoodsSkudetailService mallGoodsSkudetailService;
  76. @Autowired
  77. private IMallAddressService mallAddressService;
  78. @Autowired
  79. private IMallCartService mallCartService;
  80. @Autowired
  81. private IMallRegionService mallRegionService;
  82. @Autowired
  83. private IMallOrderService mallOrderService;
  84. @Autowired
  85. private IMallOrderDetailService mallOrderDetailService;
  86. @Autowired
  87. private IMallUserService mallUserService;
  88. @Autowired
  89. private WxPayService wxPayService;
  90. @Autowired
  91. private IMallOrderSerialService mallOrderSerialService;
  92. @Autowired
  93. private IMallShipSetService mallShipSetService;
  94. @Autowired
  95. private IMallSaleAreaService mallSaleAreaService;
  96. @Autowired
  97. private IMallShipFreeService mallShipFreeService;
  98. @Autowired
  99. private IMallShipRuleService mallShipRuleService;
  100. @Autowired
  101. private IMallCouponService mallCouponService;
  102. @Autowired
  103. private IMallCouponUserService mallCouponUserService;
  104. @ApiOperation(value = "订单列表数据", response = Rest.class)
  105. @GetMapping("/lists")
  106. public Rest index(@LoginUser Long userId, String dataType) {
  107. Map<String, Object> result = new HashMap<>();
  108. if (userId == null) {
  109. return Rest.failure(-1, "账号未授权");
  110. }
  111. QueryWrapper<MallOrder> ew = new QueryWrapper<MallOrder>();
  112. switch (dataType) {
  113. case "payment":
  114. ew.eq("order_status", 1);
  115. ew.eq("pay_status", 0);
  116. break;
  117. case "delivery":
  118. ew.eq("order_status", 1);
  119. ew.eq("pay_status", 1);
  120. ew.eq("ship_status", 0);
  121. break;
  122. case "received":
  123. ew.eq("order_status", 1);
  124. ew.eq("pay_status", 1);
  125. ew.eq("ship_status", 1);
  126. break;
  127. case "completed":
  128. ew.eq("pay_status", 1);
  129. ew.eq("ship_status", 2);
  130. break;
  131. default:
  132. break;
  133. }
  134. ew.eq("user_id", userId).orderByDesc("create_time");
  135. List<MallOrder> orderList = mallOrderService.list(ew);
  136. for (MallOrder mallOrder : orderList) {
  137. List<MallOrderDetail> details = mallOrderDetailService.list(new QueryWrapper<MallOrderDetail>().eq("order_id", mallOrder.getOrderId()));
  138. mallOrder.setGoods(details);
  139. }
  140. result.put("list", orderList);
  141. return Rest.okData(result);
  142. }
  143. /**
  144. * 订单商品详情
  145. *
  146. * @return 详情数据
  147. */
  148. @ApiOperation(value = "订单商品详情", response = Rest.class)
  149. @RequestMapping("/detail")
  150. public Rest detail(@LoginUser Long userId, Long orderId) {
  151. try {
  152. Map<String, Object> data = new HashMap<String, Object>();
  153. MallOrder mallOrder = mallOrderService.getById(orderId);
  154. List<MallOrderDetail> goods = mallOrderDetailService.list(new QueryWrapper<MallOrderDetail>().eq("order_id", mallOrder.getOrderId()));
  155. mallOrder.setGoods(goods);
  156. data.put("order", mallOrder);
  157. return Rest.okData(data);
  158. } catch (Exception e) {
  159. log.error("商品详情数据查询失败!", e.getMessage());
  160. System.out.println(e.getMessage());
  161. }
  162. return Rest.failure("服务器异常!");
  163. }
  164. /**
  165. * 立即购买
  166. */
  167. @ApiOperation(value = "立即购买", response = Rest.class)
  168. @GetMapping("/buyNow")
  169. public Rest buyNow(@LoginUser Long userId, MallCart cart, Long couponId) {
  170. Map<String, Object> data = new HashMap<>();
  171. if (userId == null) {
  172. return Rest.failure(-1, "账号未授权");
  173. }
  174. BigDecimal couponPrice = new BigDecimal(0.00);
  175. if (couponId == null || couponId == -1L) {
  176. couponId = -1L;
  177. } else {
  178. MallCoupon coupon = mallCouponService.getById(couponId);
  179. couponPrice = coupon.getDiscount();
  180. }
  181. if (cart == null) {
  182. return Rest.failure();
  183. }
  184. Long skudetailId = cart.getSkudetailId();
  185. Integer number = cart.getNumber();
  186. Long goodsId = cart.getGoodsId();
  187. if (!ObjectUtils.allNotNull(skudetailId, number, goodsId)) {
  188. return Rest.failure();
  189. }
  190. if (number <= 0) {
  191. return Rest.failure();
  192. }
  193. // 判断商品是否可以购买
  194. MallGoods goods = mallGoodService.getById(goodsId);
  195. if (goods == null || goods.getIsShelf() != 1) {
  196. return Rest.failure("商品已下架");
  197. }
  198. // 取得规格的信息,判断规格库存
  199. MallGoodsSkudetail skudetail = mallGoodsSkudetailService.getById(skudetailId);
  200. if (skudetail == null || number > skudetail.getNumber()) {
  201. return Rest.failure("库存不足");
  202. }
  203. // 筛选出可用的优惠券
  204. QueryWrapper<MallCouponUser> ew = new QueryWrapper<MallCouponUser>();
  205. ew.eq("user_id", userId);
  206. ew.eq("status", 0);
  207. ew.lt("start_time", new Date());
  208. ew.gt("end_time", new Date());
  209. List<MallCoupon> availableCoupon = new ArrayList<>();
  210. List<MallCouponUser> couponUserList = mallCouponUserService.list(ew);
  211. List<Long> couponids = couponUserList.stream().map(m -> m.getCouponId()).collect(Collectors.toList());
  212. List<MallCoupon> couponList = new ArrayList<>();
  213. if (!StringUtils.isEmpty(couponids)) {
  214. couponList = (List<MallCoupon>) mallCouponService.listByIds(couponids);
  215. }
  216. Map<Long, MallCouponUser> couponUserMaps = couponUserList.stream().collect(Collectors.toMap(MallCouponUser::getCouponId, m -> m));
  217. BigDecimal goodsAmount = new BigDecimal(0.00);
  218. BigDecimal expressPrice = new BigDecimal(0.00);
  219. goodsAmount = skudetail.getGoodPrice().multiply(new BigDecimal(number));
  220. List<MallCart> goods_list = new ArrayList<>();
  221. MallCart buyNowCart = new MallCart();
  222. buyNowCart.setGoodsId(goodsId);
  223. buyNowCart.setPicUrl(goods.getPicUrl());
  224. buyNowCart.setNumber(number);
  225. buyNowCart.setGoodPrice(skudetail.getGoodPrice());
  226. buyNowCart.setGoodsName(goods.getGoodName());
  227. buyNowCart.setSpecifications(skudetail.getSkudetails());
  228. goods_list.add(buyNowCart);
  229. // 优惠券过滤
  230. MallGoods good = mallGoodService.getById(goodsId);
  231. Long categoryId = good.getCategoryId();
  232. for (MallCoupon mallCoupon : couponList) {
  233. Integer rangType = mallCoupon.getRangeType();
  234. Long rangeRelationId = mallCoupon.getRangeRelationId();
  235. BigDecimal limit = new BigDecimal(mallCoupon.getConditionNum());
  236. if (rangType == 0 && limit.compareTo(goodsAmount) != 1) {
  237. availableCoupon.add(mallCoupon);
  238. mallCoupon.setRangeRelationName("全场通用");
  239. }
  240. if (rangType == 1 && goodsId == rangeRelationId && limit.compareTo(goodsAmount) != 1) {
  241. availableCoupon.add(mallCoupon);
  242. mallCoupon.setRangeRelationName("仅限类别" + mallCoupon.getRangeRelationName() + "使用");
  243. }
  244. if (rangType == 2 && categoryId == rangeRelationId && limit.compareTo(goodsAmount) != 1) {
  245. availableCoupon.add(mallCoupon);
  246. mallCoupon.setRangeRelationName("仅限" + mallCoupon.getRangeRelationName() + "使用");
  247. }
  248. Long couponIdKey = mallCoupon.getCouponId();
  249. MallCouponUser couponUser = couponUserMaps.get(couponIdKey);
  250. mallCoupon.setStartTime(couponUser.getStartTime());
  251. mallCoupon.setEndTime(couponUser.getEndTime());
  252. }
  253. // 查询默认收货地址
  254. Map<String, Object> params = new HashMap<String, Object>();
  255. params.put("user_id", userId);
  256. params.put("is_default", 1);
  257. MallAddress address = mallAddressService.getOne(new QueryWrapper<MallAddress>().allEq(params));
  258. List<MallAddress> addressList = mallAddressService.list(new QueryWrapper<MallAddress>().eq("user_id", userId));
  259. if (addressList.size() > 0) {
  260. data.put("exist_address", true);
  261. }
  262. if (ObjectUtils.allNotNull(address)) {
  263. // 校验当前地址是否支持配送
  264. String cityName = address.getCity();
  265. Map<String, Object> regionParams = new HashMap<String, Object>();
  266. regionParams.put("name", cityName);
  267. regionParams.put("level", 2);
  268. MallRegion mallRegion = mallRegionService.getOne(new QueryWrapper<MallRegion>().allEq(regionParams));
  269. String cityId = mallRegion.getId().toString();
  270. MallShipSet shipSet = mallShipSetService.getOne(null);
  271. // 销售区域
  272. Integer saleAreaType = shipSet.getSaleAreaType();
  273. if (saleAreaType == 0) {
  274. List<MallSaleArea> saleAreaList = mallSaleAreaService.list(null);
  275. List<String> saleIdsList = new ArrayList<String>();
  276. for (MallSaleArea mallSaleArea : saleAreaList) {
  277. String[] saleIds = Convert.toStrArray(mallSaleArea.getSaleIds());
  278. saleIdsList.addAll(Arrays.asList(saleIds));
  279. }
  280. if (!saleIdsList.contains(cityId)) {
  281. data.put("intra_region", true);
  282. data.put("express_price", expressPrice);
  283. data.put("order_pay_price", "");
  284. data.put("goods_list", goods_list);
  285. data.put("address", "");
  286. data.put("order_total_num", number);
  287. data.put("order_total_price", goodsAmount);
  288. data.put("couponId", couponId);
  289. data.put("couponPrice", couponPrice);
  290. data.put("availableCouponLength", availableCoupon.size());
  291. data.put("availableCoupon", availableCoupon);
  292. return new Rest(301, 0, data, "该区域不支持配送");
  293. }
  294. }
  295. // 自提快递
  296. Integer isSelfMention = shipSet.getIsSelfMention();
  297. if (isSelfMention == 1) {
  298. data.put("intra_region", true);
  299. data.put("express_price", expressPrice + "(用户自提费用)");
  300. data.put("order_pay_price", goodsAmount.add(expressPrice).subtract(couponPrice));
  301. data.put("goods_list", goods_list);
  302. data.put("address", address);
  303. data.put("order_total_num", number);
  304. data.put("order_total_price", goodsAmount);
  305. data.put("couponId", couponId);
  306. data.put("couponPrice", couponPrice);
  307. data.put("availableCouponLength", availableCoupon.size());
  308. data.put("availableCoupon", availableCoupon);
  309. return Rest.okData(data);
  310. }
  311. Integer freightType = shipSet.getFreightType();
  312. if (freightType == 1) {
  313. data.put("intra_region", true);
  314. data.put("express_price", expressPrice);
  315. data.put("order_pay_price", goodsAmount.add(expressPrice).subtract(couponPrice));
  316. data.put("goods_list", goods_list);
  317. data.put("address", address);
  318. data.put("order_total_num", number);
  319. data.put("order_total_price", goodsAmount);
  320. data.put("couponId", couponId);
  321. data.put("couponPrice", couponPrice);
  322. data.put("availableCouponLength", availableCoupon.size());
  323. data.put("availableCoupon", availableCoupon);
  324. return Rest.okData(data);
  325. }
  326. // 快递校验是否满足包邮条件
  327. List<MallShipFree> shipfreeList = mallShipFreeService.list(null);
  328. boolean isFreeship = false;
  329. for (MallShipFree shipfree : shipfreeList) {
  330. String[] shipfreeIds = Convert.toStrArray(shipfree.getFreeshipIds());
  331. long count = Arrays.stream(shipfreeIds).filter(str -> str.equals(cityId)).count();
  332. if (count > 0) {
  333. if (!(shipfree.getWeightFree().compareTo(skudetail.getGoodWeight()) == -1) || !(shipfree.getExpenseFee().compareTo(skudetail.getGoodPrice()) == -1)) {
  334. isFreeship = true;
  335. break;
  336. }
  337. }
  338. }
  339. // 包邮
  340. if (isFreeship) {
  341. data.put("intra_region", true);
  342. data.put("express_price", expressPrice);
  343. data.put("order_pay_price", goodsAmount.add(expressPrice).subtract(couponPrice));
  344. data.put("goods_list", goods_list);
  345. data.put("address", address);
  346. data.put("order_total_num", number);
  347. data.put("order_total_price", goodsAmount);
  348. data.put("couponId", couponId);
  349. data.put("couponPrice", couponPrice);
  350. data.put("availableCouponLength", availableCoupon.size());
  351. data.put("availableCoupon", availableCoupon);
  352. return Rest.okData(data);
  353. }
  354. // 计算自定义运费
  355. BigDecimal defaultWeight = shipSet.getDefaultWeight();
  356. BigDecimal defaultExpense = shipSet.getDefaultExpense();
  357. BigDecimal continueWeight = new BigDecimal(1.00);
  358. BigDecimal continueExpense = shipSet.getContinueExpense();
  359. List<MallShipRule> shipRuleList = mallShipRuleService.list(null);
  360. for (MallShipRule shipRule : shipRuleList) {
  361. String[] shipRuleIds = Convert.toStrArray(shipRule.getShipIds());
  362. long count = Arrays.stream(shipRuleIds).filter(str -> str.equals(cityId)).count();
  363. if (count > 0) {
  364. defaultWeight = shipRule.getDefaultWeight();
  365. defaultExpense = shipRule.getDefaultExpense();
  366. continueWeight = shipRule.getContinueWeight();
  367. continueExpense = shipRule.getContinueExpense();
  368. break;
  369. }
  370. }
  371. BigDecimal weight = skudetail.getGoodWeight();
  372. // 重量小于等于首重
  373. if (!(weight.compareTo(defaultWeight) == 1)) {
  374. data.put("express_price", defaultExpense);
  375. data.put("order_pay_price", goodsAmount.add(defaultExpense).subtract(couponPrice));
  376. } else {
  377. BigDecimal totalAdditional = weight.subtract(defaultWeight).divide(continueWeight);
  378. BigDecimal totalAdditionalFee = defaultExpense.add(totalAdditional.multiply(continueExpense));
  379. data.put("express_price", totalAdditionalFee);
  380. data.put("order_pay_price", goodsAmount.add(totalAdditionalFee).subtract(couponPrice));
  381. }
  382. data.put("intra_region", true);
  383. } else {
  384. data.put("intra_region", false);
  385. }
  386. data.put("goods_list", goods_list);
  387. data.put("address", address);
  388. data.put("order_total_num", number);
  389. data.put("order_total_price", goodsAmount);
  390. data.put("couponId", couponId);
  391. data.put("couponPrice", couponPrice);
  392. data.put("availableCouponLength", availableCoupon.size());
  393. data.put("availableCoupon", availableCoupon);
  394. return Rest.okData(data);
  395. }
  396. /**
  397. * 立即购买下单
  398. */
  399. @ApiOperation(value = "立即购买下单", response = Rest.class)
  400. @PostMapping("/addOrderBuyNow")
  401. @Transactional
  402. public Rest addOrderBuyNow(@RequestBody String body, HttpServletRequest request, @LoginUser Long userId) {
  403. Map<String, Object> data = new HashMap<>();
  404. JSONObject json = JSONObject.parseObject(body);
  405. String skudetailId = json.getString("skudetailId");
  406. Integer number = json.getInteger("number");
  407. String goodsId = json.getString("goodsId");
  408. Long couponId = json.getLong("couponId");
  409. if (couponId == null) {
  410. return Rest.failure("优惠券不可使用");
  411. }
  412. BigDecimal couponPrice = new BigDecimal(0.00);
  413. if (couponId != -1L) {
  414. MallCoupon coupon = mallCouponService.getById(couponId);
  415. couponPrice = coupon.getDiscount();
  416. }
  417. if (!ObjectUtils.allNotNull(skudetailId, number, goodsId)) {
  418. return Rest.failure();
  419. }
  420. if (number <= 0) {
  421. return Rest.failure();
  422. }
  423. // 判断商品是否可以购买
  424. MallGoods goods = mallGoodService.getById(goodsId);
  425. if (goods == null || goods.getIsShelf() != 1) {
  426. return Rest.failure("商品已下架");
  427. }
  428. // 取得规格的信息,判断规格库存
  429. MallGoodsSkudetail skudetail = mallGoodsSkudetailService.getById(skudetailId);
  430. if (skudetail == null || number > skudetail.getNumber()) {
  431. return Rest.failure("库存不足,购买失败!");
  432. }
  433. BigDecimal goodsAmount = new BigDecimal(0.00);
  434. BigDecimal expressPrice = new BigDecimal(0.00);
  435. goodsAmount = skudetail.getGoodPrice().multiply(new BigDecimal(number));
  436. // 查询默认收货地址
  437. Map<String, Object> params = new HashMap<String, Object>();
  438. params.put("user_id", userId);
  439. params.put("is_default", 1);
  440. MallAddress address = mallAddressService.getOne(new QueryWrapper<MallAddress>().allEq(params));
  441. if (ObjectUtils.allNotNull(address)) {
  442. // 校验当前地址是否支持配送
  443. String cityName = address.getCity();
  444. Map<String, Object> regionParams = new HashMap<String, Object>();
  445. regionParams.put("name", cityName);
  446. regionParams.put("level", 2);
  447. MallRegion mallRegion = mallRegionService.getOne(new QueryWrapper<MallRegion>().allEq(regionParams));
  448. String cityId = mallRegion.getId().toString();
  449. MallShipSet shipSet = mallShipSetService.getOne(null);
  450. // 销售区域
  451. Integer saleAreaType = shipSet.getSaleAreaType();
  452. if (saleAreaType == 0) {
  453. List<MallSaleArea> saleAreaList = mallSaleAreaService.list(null);
  454. List<String> saleIdsList = new ArrayList<String>();
  455. for (MallSaleArea mallSaleArea : saleAreaList) {
  456. String[] saleIds = Convert.toStrArray(mallSaleArea.getSaleIds());
  457. saleIdsList.addAll(Arrays.asList(saleIds));
  458. }
  459. if (!saleIdsList.contains(cityId)) {
  460. return Rest.failure("该区域不支持配送");
  461. }
  462. }
  463. // 自提快递
  464. Integer isSelfMention = shipSet.getIsSelfMention();
  465. if (isSelfMention == 1) {
  466. expressPrice = new BigDecimal(0.00);
  467. }
  468. Integer freightType = shipSet.getFreightType();
  469. if (freightType == 1) {
  470. expressPrice = new BigDecimal(0.00);
  471. }
  472. if (isSelfMention == 0 && freightType == 0) {
  473. // 快递校验是否满足包邮条件
  474. List<MallShipFree> shipfreeList = mallShipFreeService.list(null);
  475. boolean isFreeship = false;
  476. for (MallShipFree shipfree : shipfreeList) {
  477. String[] shipfreeIds = Convert.toStrArray(shipfree.getFreeshipIds());
  478. long count = Arrays.stream(shipfreeIds).filter(str -> str.equals(cityId)).count();
  479. if (count > 0) {
  480. if (!(shipfree.getWeightFree().compareTo(skudetail.getGoodWeight()) == -1) || !(shipfree.getExpenseFee().compareTo(skudetail.getGoodPrice()) == -1)) {
  481. isFreeship = true;
  482. break;
  483. }
  484. }
  485. }
  486. if (isFreeship) { // 包邮
  487. expressPrice = new BigDecimal(0.00);
  488. } else { // 计算自定义运费
  489. BigDecimal defaultWeight = shipSet.getDefaultWeight();
  490. BigDecimal defaultExpense = shipSet.getDefaultExpense();
  491. BigDecimal continueWeight = new BigDecimal(1.00);
  492. BigDecimal continueExpense = shipSet.getContinueExpense();
  493. List<MallShipRule> shipRuleList = mallShipRuleService.list(null);
  494. for (MallShipRule shipRule : shipRuleList) {
  495. String[] shipRuleIds = Convert.toStrArray(shipRule.getShipIds());
  496. long count = Arrays.stream(shipRuleIds).filter(str -> str.equals(cityId)).count();
  497. if (count > 0) {
  498. defaultWeight = shipRule.getDefaultWeight();
  499. defaultExpense = shipRule.getDefaultExpense();
  500. continueWeight = shipRule.getContinueWeight();
  501. continueExpense = shipRule.getContinueExpense();
  502. break;
  503. }
  504. }
  505. BigDecimal weight = skudetail.getGoodWeight();
  506. // 重量小于等于首重
  507. if (!(weight.compareTo(defaultWeight) == 1)) {
  508. expressPrice = defaultExpense;
  509. } else {
  510. BigDecimal totalAdditional = weight.subtract(defaultWeight).divide(continueWeight);
  511. BigDecimal totalAdditionalFee = defaultExpense.add(totalAdditional.multiply(continueExpense));
  512. expressPrice = totalAdditionalFee;
  513. }
  514. }
  515. }
  516. } else {
  517. return Rest.failure("请先选择收货地址");
  518. }
  519. // 冻结库存
  520. if (mallGoodsSkudetailService.reduceStock(skudetail.getSkudetailId(), number) <= 0) {
  521. return Rest.failure("库存不足,购买失败!");
  522. }
  523. // 生成订单
  524. MallOrder mallOrder = new MallOrder();
  525. mallOrder.setOrderId(DistributedIdWorker.nextId());
  526. mallOrder.setUserId(userId);
  527. mallOrder.setOrderSn(Long.valueOf(this.getSerial("order_no")));
  528. mallOrder.setOrderStatus(1);
  529. mallOrder.setPayStatus(0);
  530. mallOrder.setShipStatus(0);
  531. mallOrder.setConsignee(address.getName());
  532. mallOrder.setMobile(address.getPhone());
  533. String consigerAddress = address.getProvince() + address.getCity() + address.getRegion() + address.getDetail();
  534. mallOrder.setAddress(consigerAddress);
  535. mallOrder.setTotalPrice(goodsAmount);
  536. mallOrder.setShipPrice(expressPrice);
  537. mallOrder.setCouponPrice(couponPrice);
  538. mallOrder.setOrderPrice(goodsAmount.add(expressPrice).subtract(couponPrice));
  539. if (mallOrderService.save(mallOrder)) {
  540. MallOrderDetail mallOrderDetail = new MallOrderDetail();
  541. mallOrderDetail.setOrderDetailId(DistributedIdWorker.nextId());
  542. mallOrderDetail.setOrderId(mallOrder.getOrderId());
  543. mallOrderDetail.setGoodsId(goods.getGoodsId());
  544. mallOrderDetail.setGoodsName(goods.getGoodName());
  545. mallOrderDetail.setPicUrl(goods.getPicUrl());
  546. mallOrderDetail.setSkuDetailId(skudetail.getSkudetailId());
  547. mallOrderDetail.setGoodPrice(skudetail.getGoodPrice());
  548. mallOrderDetail.setGoodsSn(skudetail.getBusinessCode());
  549. mallOrderDetail.setNumber(number);
  550. mallOrderDetail.setSpecifications(skudetail.getSkudetails());
  551. mallOrderDetail.setComment(0L);
  552. mallOrderDetailService.save(mallOrderDetail);
  553. // 使用优惠券则更新优惠券状态
  554. if (couponId != -1L) {
  555. MallCouponUser couponUser = new MallCouponUser();
  556. couponUser.setOrderId(mallOrder.getOrderId());
  557. couponUser.setUsedTime(new Date());
  558. couponUser.setStatus(1);
  559. mallCouponUserService.update(couponUser, new QueryWrapper<MallCouponUser>().eq("user_id", userId).eq("coupon_id", couponId));
  560. }
  561. }
  562. // 微信支付
  563. MallUser user = mallUserService.getById(userId);
  564. WxPayMpOrderResult result = null;
  565. try {
  566. WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
  567. orderRequest.setOutTradeNo(String.valueOf(mallOrder.getOrderSn()));
  568. orderRequest.setOpenid(user.getWeixinOpenid());
  569. orderRequest.setBody("订单:" + mallOrder.getOrderSn());
  570. // 元转成分
  571. int fee = 0;
  572. BigDecimal actualPrice = mallOrder.getTotalPrice().subtract(mallOrder.getShipPrice());
  573. fee = actualPrice.multiply(new BigDecimal(100)).intValue();
  574. orderRequest.setTotalFee(fee);
  575. orderRequest.setSpbillCreateIp(IpUtils.getIpAddr(request));
  576. result = wxPayService.createOrder(orderRequest);
  577. data.put("payment", result);
  578. } catch (Exception e) {
  579. e.printStackTrace();
  580. Map<String, Object> resultStr = new HashMap<>();
  581. resultStr.put("timeStamp", "");
  582. resultStr.put("nonceStr", "");
  583. resultStr.put("packageValue", "");
  584. resultStr.put("paySign", "");
  585. data.put("payment", resultStr);
  586. }
  587. return Rest.okData(data);
  588. }
  589. /**
  590. * 购物车购买
  591. */
  592. @ApiOperation(value = "购物车购买", response = Rest.class)
  593. @GetMapping("/cart")
  594. public Rest cart(@LoginUser Long userId, Long couponId) {
  595. Map<String, Object> data = new HashMap<>();
  596. if (userId == null) {
  597. return Rest.failure(-1, "账号未授权");
  598. }
  599. BigDecimal couponPrice = new BigDecimal(0.00);
  600. if (couponId == null || couponId == -1L) {
  601. couponId = -1L;
  602. } else {
  603. MallCoupon coupon = mallCouponService.getById(couponId);
  604. couponPrice = coupon.getDiscount();
  605. }
  606. // 查询默认收货地址
  607. Map<String, Object> params = new HashMap<String, Object>();
  608. params.put("user_id", userId);
  609. params.put("is_default", 1);
  610. MallAddress address = mallAddressService.getOne(new QueryWrapper<MallAddress>().allEq(params));
  611. List<MallAddress> addressList = mallAddressService.list(new QueryWrapper<MallAddress>().eq("user_id", userId));
  612. List<MallCart> cartList = mallCartService.list(new QueryWrapper<MallCart>().eq("user_id", userId));
  613. // 筛选出可用的优惠券
  614. QueryWrapper<MallCouponUser> ew = new QueryWrapper<MallCouponUser>();
  615. ew.eq("user_id", userId);
  616. ew.eq("status", 0);
  617. ew.lt("start_time", new Date());
  618. ew.gt("end_time", new Date());
  619. List<MallCoupon> availableCoupon = new ArrayList<>();
  620. List<MallCouponUser> couponUserList = mallCouponUserService.list(ew);
  621. List<Long> couponIds = couponUserList.stream().map(m -> m.getCouponId()).collect(Collectors.toList());
  622. List<MallCoupon> couponList = new ArrayList<>();
  623. if (!StringUtils.isEmpty(couponIds)) {
  624. couponList = (List<MallCoupon>) mallCouponService.listByIds(couponIds);
  625. }
  626. Map<Long, MallCouponUser> couponUserMaps = couponUserList.stream().collect(Collectors.toMap(MallCouponUser::getCouponId, m -> m));
  627. Integer goodsCount = 0;
  628. BigDecimal goodsAmount = new BigDecimal(0.00);
  629. BigDecimal expressPrice = new BigDecimal(0.00);
  630. BigDecimal totalWeight = new BigDecimal(0.00);
  631. // 商品优惠价格过滤
  632. Map<Long, BigDecimal> goodMap = new HashMap<>();
  633. // 商品分类优惠价格过滤
  634. Map<Long, BigDecimal> categoryMap = new HashMap<>();
  635. for (MallCart cart : cartList) {
  636. // 判断商品是否可以购买
  637. MallGoods goods = mallGoodService.getById(cart.getGoodsId());
  638. if (goods == null || goods.getIsShelf() != 1) {
  639. return Rest.failure("商品已下架");
  640. }
  641. MallGoodsSkudetail skudetail = mallGoodsSkudetailService.getById(cart.getSkudetailId());
  642. // 取得规格的信息,判断规格库存
  643. if (skudetail == null || cart.getNumber() > skudetail.getNumber()) {
  644. return Rest.failure("库存不足,购买失败!");
  645. }
  646. goodsCount += cart.getNumber();
  647. BigDecimal goodPrice = skudetail.getGoodPrice().multiply(new BigDecimal(cart.getNumber()));
  648. goodsAmount = goodsAmount.add(goodPrice);
  649. totalWeight = totalWeight.add(skudetail.getGoodWeight().multiply(new BigDecimal(cart.getNumber())));
  650. cart.setPicUrl(goods.getPicUrl());
  651. cart.setGoodPrice(skudetail.getGoodPrice());
  652. cart.setGoodsName(goods.getGoodName());
  653. cart.setSpecifications(skudetail.getSkudetails());
  654. Long goodId = goods.getGoodsId();
  655. Long categoryId = goods.getCategoryId();
  656. if (goodMap.containsKey(goodId)) {
  657. goodMap.put(goodId, goodPrice.add(goodMap.get(goodId)));
  658. } else {
  659. goodMap.put(goodId, goodPrice);
  660. }
  661. if (categoryMap.containsKey(categoryId)) {
  662. categoryMap.put(categoryId, goodPrice.add(categoryMap.get(categoryId)));
  663. } else {
  664. categoryMap.put(categoryId, goodPrice);
  665. }
  666. }
  667. for (MallCoupon mallCoupon : couponList) {
  668. Integer rangType = mallCoupon.getRangeType();
  669. Long rangeRelationId = mallCoupon.getRangeRelationId();
  670. BigDecimal limit = new BigDecimal(mallCoupon.getConditionNum());
  671. if (rangType == 0 && limit.compareTo(goodsAmount) != 1) {
  672. availableCoupon.add(mallCoupon);
  673. mallCoupon.setRangeRelationName("全场通用");
  674. }
  675. if (rangType == 1 && categoryMap.containsKey(rangeRelationId) && limit.compareTo(categoryMap.get(rangeRelationId)) != 1) {
  676. availableCoupon.add(mallCoupon);
  677. mallCoupon.setRangeRelationName("仅限类别" + mallCoupon.getRangeRelationName() + "使用");
  678. }
  679. if (rangType == 2 && goodMap.containsKey(rangeRelationId) && limit.compareTo(goodMap.get(rangeRelationId)) != 1) {
  680. availableCoupon.add(mallCoupon);
  681. mallCoupon.setRangeRelationName("仅限" + mallCoupon.getRangeRelationName() + "使用");
  682. }
  683. Long couponIdKey = mallCoupon.getCouponId();
  684. MallCouponUser couponUser = couponUserMaps.get(couponIdKey);
  685. mallCoupon.setStartTime(couponUser.getStartTime());
  686. mallCoupon.setEndTime(couponUser.getEndTime());
  687. }
  688. if (addressList.size() > 0) {
  689. data.put("exist_address", true);
  690. }
  691. if (ObjectUtils.allNotNull(address)) {
  692. // 校验当前地址是否支持配送
  693. String cityName = address.getCity();
  694. Map<String, Object> regionParams = new HashMap<String, Object>();
  695. regionParams.put("name", cityName);
  696. regionParams.put("level", 2);
  697. MallRegion mallRegion = mallRegionService.getOne(new QueryWrapper<MallRegion>().allEq(regionParams));
  698. String cityId = mallRegion.getId().toString();
  699. MallShipSet shipSet = mallShipSetService.getOne(null);
  700. // 销售区域
  701. Integer saleAreaType = shipSet.getSaleAreaType();
  702. if (saleAreaType == 0) {
  703. List<MallSaleArea> saleAreaList = mallSaleAreaService.list(null);
  704. List<String> saleIdsList = new ArrayList<String>();
  705. for (MallSaleArea mallSaleArea : saleAreaList) {
  706. String[] saleIds = Convert.toStrArray(mallSaleArea.getSaleIds());
  707. saleIdsList.addAll(Arrays.asList(saleIds));
  708. }
  709. if (!saleIdsList.contains(cityId)) {
  710. data.put("intra_region", true);
  711. data.put("express_price", 0.00);
  712. data.put("goods_list", cartList);
  713. data.put("address", "");
  714. data.put("order_total_num", goodsCount);
  715. data.put("order_total_price", goodsAmount);
  716. data.put("order_pay_price", "");
  717. data.put("couponId", couponId);
  718. data.put("couponPrice", couponPrice);
  719. data.put("availableCouponLength", availableCoupon.size());
  720. data.put("availableCoupon", availableCoupon);
  721. return new Rest(301, 0, data, "该区域不支持配送");
  722. }
  723. }
  724. // 自提快递
  725. Integer isSelfMention = shipSet.getIsSelfMention();
  726. if (isSelfMention == 1) {
  727. data.put("intra_region", true);
  728. data.put("express_price", 0.00 + "(用户自提费用)");
  729. data.put("goods_list", cartList);
  730. data.put("address", address);
  731. data.put("order_total_num", goodsCount);
  732. data.put("order_total_price", goodsAmount);
  733. data.put("order_pay_price", expressPrice.add(goodsAmount).subtract(couponPrice));
  734. data.put("couponId", couponId);
  735. data.put("couponPrice", couponPrice);
  736. data.put("availableCouponLength", availableCoupon.size());
  737. data.put("availableCoupon", availableCoupon);
  738. return Rest.okData(data);
  739. }
  740. Integer freightType = shipSet.getFreightType();
  741. if (freightType == 1) {
  742. data.put("intra_region", true);
  743. data.put("express_price", 0.00);
  744. data.put("goods_list", cartList);
  745. data.put("address", address);
  746. data.put("order_total_num", goodsCount);
  747. data.put("order_total_price", goodsAmount);
  748. data.put("order_pay_price", expressPrice.add(goodsAmount).subtract(couponPrice));
  749. data.put("couponId", couponId);
  750. data.put("couponPrice", couponPrice);
  751. data.put("availableCouponLength", availableCoupon.size());
  752. data.put("availableCoupon", availableCoupon);
  753. return Rest.okData(data);
  754. }
  755. // 快递校验是否满足包邮条件
  756. List<MallShipFree> shipfreeList = mallShipFreeService.list(null);
  757. boolean isFreeship = false;
  758. for (MallShipFree shipfree : shipfreeList) {
  759. String[] shipfreeIds = Convert.toStrArray(shipfree.getFreeshipIds());
  760. long count = Arrays.stream(shipfreeIds).filter(str -> str.equals(cityId)).count();
  761. if (count > 0) {
  762. if (!(shipfree.getWeightFree().compareTo(totalWeight) == -1) || !(shipfree.getExpenseFee().compareTo(goodsAmount) == -1)) {
  763. isFreeship = true;
  764. break;
  765. }
  766. }
  767. }
  768. // 包邮
  769. if (isFreeship) {
  770. data.put("intra_region", true);
  771. data.put("express_price", 0.00);
  772. data.put("goods_list", cartList);
  773. data.put("address", address);
  774. data.put("order_total_num", goodsCount);
  775. data.put("order_total_price", goodsAmount);
  776. data.put("order_pay_price", expressPrice.add(goodsAmount).subtract(couponPrice));
  777. data.put("couponId", couponId);
  778. data.put("couponPrice", couponPrice);
  779. data.put("availableCouponLength", availableCoupon.size());
  780. data.put("availableCoupon", availableCoupon);
  781. return Rest.okData(data);
  782. }
  783. // 计算自定义运费
  784. BigDecimal defaultWeight = shipSet.getDefaultWeight();
  785. BigDecimal defaultExpense = shipSet.getDefaultExpense();
  786. BigDecimal continueWeight = new BigDecimal(1.00);
  787. BigDecimal continueExpense = shipSet.getContinueExpense();
  788. List<MallShipRule> shipRuleList = mallShipRuleService.list(null);
  789. for (MallShipRule shipRule : shipRuleList) {
  790. String[] shipRuleIds = Convert.toStrArray(shipRule.getShipIds());
  791. long count = Arrays.stream(shipRuleIds).filter(str -> str.equals(cityId)).count();
  792. if (count > 0) {
  793. defaultWeight = shipRule.getDefaultWeight();
  794. defaultExpense = shipRule.getDefaultExpense();
  795. continueWeight = shipRule.getContinueWeight();
  796. continueExpense = shipRule.getContinueExpense();
  797. break;
  798. }
  799. }
  800. // 重量小于等于首重
  801. if (!(totalWeight.compareTo(defaultWeight) == 1)) {
  802. data.put("express_price", defaultExpense);
  803. } else {
  804. BigDecimal totalAdditional = totalWeight.subtract(defaultWeight).divide(continueWeight);
  805. BigDecimal totalAdditionalFee = defaultExpense.add(totalAdditional.multiply(continueExpense));
  806. data.put("express_price", totalAdditionalFee);
  807. }
  808. data.put("intra_region", true);
  809. } else {
  810. data.put("intra_region", false);
  811. }
  812. data.put("goods_list", cartList);
  813. data.put("address", address);
  814. data.put("order_total_num", goodsCount);
  815. data.put("order_total_price", goodsAmount);
  816. data.put("express_price", expressPrice);
  817. data.put("order_pay_price", goodsAmount.add(expressPrice).subtract(couponPrice));
  818. data.put("couponId", couponId);
  819. data.put("couponPrice", couponPrice);
  820. data.put("availableCouponLength", availableCoupon.size());
  821. data.put("availableCoupon", availableCoupon);
  822. return Rest.okData(data);
  823. }
  824. /**
  825. * 购物车购买-下单
  826. */
  827. @ApiOperation(value = "购物车购买-下单", response = Rest.class)
  828. @PostMapping("/addOrderFromCart")
  829. @Transactional
  830. public Rest addOrderFromCart(@LoginUser Long userId, HttpServletRequest request, @RequestBody String body) {
  831. Map<String, Object> data = new HashMap<>();
  832. try {
  833. if (userId == null) {
  834. return Rest.failure(-1, "账号未授权");
  835. }
  836. JSONObject json = JSONObject.parseObject(body);
  837. Long couponId = json.getLong("couponId");
  838. if (couponId == null) {
  839. return Rest.failure("优惠券不可使用");
  840. }
  841. BigDecimal couponPrice = new BigDecimal(0.00);
  842. if (couponId != -1L) {
  843. MallCoupon coupon = mallCouponService.getById(couponId);
  844. couponPrice = coupon.getDiscount();
  845. }
  846. Map<String, Object> params = new HashMap<String, Object>();
  847. params.put("user_id", userId);
  848. params.put("is_default", 1);
  849. MallAddress address = mallAddressService.getOne(new QueryWrapper<MallAddress>().allEq(params));
  850. List<MallCart> cartList = mallCartService.list(new QueryWrapper<MallCart>().eq("user_id", userId));
  851. MallUser user = mallUserService.getById(userId);
  852. List<MallOrderDetail> goodList = new ArrayList<>();
  853. Integer goodsCount = 0;
  854. BigDecimal goodsAmount = new BigDecimal(0.00);
  855. BigDecimal expressPrice = new BigDecimal(0.00);
  856. BigDecimal totalWeight = new BigDecimal(0.00);
  857. List<Long> cartIds = new ArrayList<>();
  858. for (MallCart cart : cartList) {
  859. cartIds.add(cart.getCartId());
  860. MallGoods goods = mallGoodService.getById(cart.getGoodsId());
  861. if (goods == null || goods.getIsShelf() != 1) {
  862. return Rest.failure("商品已下架");
  863. }
  864. MallGoodsSkudetail skudetail = mallGoodsSkudetailService.getById(cart.getSkudetailId());
  865. if (skudetail == null || cart.getNumber() > skudetail.getNumber()) {
  866. return Rest.failure("商品【"+ goods.getGoodName() +"】库存不足,购买失败!");
  867. }
  868. goodsCount += cart.getNumber();
  869. goodsAmount = goodsAmount.add(skudetail.getGoodPrice().multiply(new BigDecimal(cart.getNumber())));
  870. totalWeight = totalWeight.add(skudetail.getGoodWeight().multiply(new BigDecimal(cart.getNumber())));
  871. MallOrderDetail mallOrderDetail = new MallOrderDetail();
  872. mallOrderDetail.setOrderDetailId(DistributedIdWorker.nextId());
  873. mallOrderDetail.setGoodsId(goods.getGoodsId());
  874. mallOrderDetail.setGoodsName(goods.getGoodName());
  875. mallOrderDetail.setPicUrl(goods.getPicUrl());
  876. mallOrderDetail.setSkuDetailId(skudetail.getSkudetailId());
  877. mallOrderDetail.setGoodPrice(skudetail.getGoodPrice());
  878. mallOrderDetail.setGoodsSn(skudetail.getBusinessCode());
  879. mallOrderDetail.setNumber(cart.getNumber());
  880. mallOrderDetail.setSpecifications(skudetail.getSkudetails());
  881. mallOrderDetail.setComment(0L);
  882. goodList.add(mallOrderDetail);
  883. // 冻结库存
  884. if (skudetail.getNumber() - cart.getNumber() < 0) {
  885. return Rest.failure("商品库存不足,购买失败!");
  886. }
  887. // 更新库存
  888. if (mallGoodsSkudetailService.reduceStock(skudetail.getSkudetailId(), cart.getNumber()) == 0) {
  889. return Rest.failure("商品库存不足,购买失败!");
  890. }
  891. ;
  892. }
  893. if (ObjectUtils.allNotNull(address)) {
  894. // 校验当前地址是否支持配送
  895. String cityName = address.getCity();
  896. Map<String, Object> regionParams = new HashMap<String, Object>();
  897. regionParams.put("name", cityName);
  898. regionParams.put("level", 2);
  899. MallRegion mallRegion = mallRegionService.getOne(new QueryWrapper<MallRegion>().allEq(regionParams));
  900. String cityId = mallRegion.getId().toString();
  901. MallShipSet shipSet = mallShipSetService.getOne(null);
  902. // 销售区域
  903. Integer saleAreaType = shipSet.getSaleAreaType();
  904. if (saleAreaType == 0) {
  905. List<MallSaleArea> saleAreaList = mallSaleAreaService.list(null);
  906. List<String> saleIdsList = new ArrayList<String>();
  907. for (MallSaleArea mallSaleArea : saleAreaList) {
  908. String[] saleIds = Convert.toStrArray(mallSaleArea.getSaleIds());
  909. saleIdsList.addAll(Arrays.asList(saleIds));
  910. }
  911. if (!saleIdsList.contains(cityId)) {
  912. return Rest.failure("该区域不支持配送");
  913. }
  914. }
  915. // 自提快递
  916. Integer isSelfMention = shipSet.getIsSelfMention();
  917. if (isSelfMention == 1) {
  918. expressPrice = new BigDecimal(0.00);
  919. }
  920. Integer freightType = shipSet.getFreightType();
  921. if (freightType == 1) {
  922. expressPrice = new BigDecimal(0.00);
  923. }
  924. if (isSelfMention == 0 && freightType == 0) {
  925. // 快递校验是否满足包邮条件
  926. List<MallShipFree> shipfreeList = mallShipFreeService.list(null);
  927. boolean isFreeship = false;
  928. for (MallShipFree shipfree : shipfreeList) {
  929. String[] shipfreeIds = Convert.toStrArray(shipfree.getFreeshipIds());
  930. long count = Arrays.stream(shipfreeIds).filter(str -> str.equals(cityId)).count();
  931. if (count > 0) {
  932. if (!(shipfree.getWeightFree().compareTo(totalWeight) == -1) || !(shipfree.getExpenseFee().compareTo(goodsAmount) == -1)) {
  933. isFreeship = true;
  934. break;
  935. }
  936. }
  937. }
  938. // 包邮
  939. if (isFreeship) {
  940. expressPrice = new BigDecimal(0.00);
  941. } else {
  942. // 计算自定义运费
  943. BigDecimal defaultWeight = shipSet.getDefaultWeight();
  944. BigDecimal defaultExpense = shipSet.getDefaultExpense();
  945. BigDecimal continueWeight = new BigDecimal(1.00);
  946. BigDecimal continueExpense = shipSet.getContinueExpense();
  947. List<MallShipRule> shipRuleList = mallShipRuleService.list(null);
  948. for (MallShipRule shipRule : shipRuleList) {
  949. String[] shipRuleIds = Convert.toStrArray(shipRule.getShipIds());
  950. long count = Arrays.stream(shipRuleIds).filter(str -> str.equals(cityId)).count();
  951. if (count > 0) {
  952. defaultWeight = shipRule.getDefaultWeight();
  953. defaultExpense = shipRule.getDefaultExpense();
  954. continueWeight = shipRule.getContinueWeight();
  955. continueExpense = shipRule.getContinueExpense();
  956. break;
  957. }
  958. }
  959. // 重量小于等于首重
  960. if (!(totalWeight.compareTo(defaultWeight) == 1)) {
  961. expressPrice = defaultExpense;
  962. } else {
  963. BigDecimal totalAdditional = totalWeight.subtract(defaultWeight).divide(continueWeight);
  964. BigDecimal totalAdditionalFee = defaultExpense.add(totalAdditional.multiply(continueExpense));
  965. expressPrice = totalAdditionalFee;
  966. }
  967. }
  968. }
  969. } else {
  970. data.put("intra_region", false);
  971. }
  972. // 订单编号
  973. MallOrder mallOrder = new MallOrder();
  974. mallOrder.setOrderId(DistributedIdWorker.nextId());
  975. mallOrder.setUserId(userId);
  976. mallOrder.setOrderSn(Long.valueOf(this.getSerial("order_no")));
  977. mallOrder.setOrderStatus(1);
  978. mallOrder.setPayStatus(0);
  979. mallOrder.setShipStatus(0);
  980. mallOrder.setConsignee(address.getName());
  981. mallOrder.setMobile(address.getPhone());
  982. String consigerAddress = address.getProvince() + address.getCity() + address.getRegion() + address.getDetail();
  983. mallOrder.setAddress(consigerAddress);
  984. mallOrder.setTotalPrice(goodsAmount);
  985. mallOrder.setShipPrice(expressPrice);
  986. mallOrder.setCouponPrice(couponPrice);
  987. mallOrder.setOrderPrice(goodsAmount.add(expressPrice).subtract(couponPrice));
  988. // 订单生成成功
  989. if (mallOrderService.save(mallOrder)) {
  990. for (MallOrderDetail mallOrderDetail : goodList) {
  991. mallOrderDetail.setOrderId(mallOrder.getOrderId());
  992. }
  993. // 保存订单明细
  994. mallOrderDetailService.saveBatch(goodList);
  995. // 商品移出购物车
  996. mallCartService.removeByIds(cartIds);
  997. // 使用优惠券则更新优惠券状态
  998. if (couponId != -1L) {
  999. MallCouponUser couponUser = new MallCouponUser();
  1000. couponUser.setOrderId(mallOrder.getOrderId());
  1001. couponUser.setUsedTime(new Date());
  1002. couponUser.setStatus(1);
  1003. mallCouponUserService.update(couponUser, new QueryWrapper<MallCouponUser>().eq("user_id", userId).eq("coupon_id", couponId));
  1004. }
  1005. }
  1006. WxPayMpOrderResult result = null;
  1007. WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
  1008. orderRequest.setOutTradeNo(String.valueOf(mallOrder.getOrderSn()));
  1009. orderRequest.setOpenid(user.getWeixinOpenid());
  1010. orderRequest.setBody("订单:" + mallOrder.getOrderSn());
  1011. // 元转成分
  1012. int fee = 0;
  1013. BigDecimal actualPrice = mallOrder.getOrderPrice();
  1014. fee = actualPrice.multiply(new BigDecimal(100)).intValue();
  1015. orderRequest.setTotalFee(fee);
  1016. orderRequest.setSpbillCreateIp(IpUtils.getIpAddr(request));
  1017. result = wxPayService.createOrder(orderRequest);
  1018. data.put("payment", result);
  1019. } catch (Exception e) {
  1020. e.printStackTrace();
  1021. Map<String, Object> resultStr = new HashMap<>();
  1022. resultStr.put("timeStamp", "");
  1023. resultStr.put("nonceStr", "");
  1024. resultStr.put("packageValue", "");
  1025. resultStr.put("paySign", "");
  1026. data.put("payment", resultStr);
  1027. }
  1028. return Rest.okData(data);
  1029. }
  1030. private String getSerial(String prefix) {
  1031. Timestamp nowDate = new Timestamp(System.currentTimeMillis());
  1032. SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
  1033. String nowDateIntString = formatter.format(nowDate);
  1034. String serialCode = prefix + "_" + nowDateIntString.substring(0, 8);
  1035. Integer serialNo = 1;
  1036. List<MallOrderSerial> mallSerials = mallOrderSerialService.list(new QueryWrapper<MallOrderSerial>().eq("serial_code", serialCode));
  1037. if (StringUtils.isNotEmpty(mallSerials)) {
  1038. MallOrderSerial mallSerial = mallSerials.get(0);
  1039. serialNo = (int) (mallSerial.getSerialNo() + 1);
  1040. mallSerial.setSerialNo(mallSerial.getSerialNo() + 1);
  1041. mallOrderSerialService.updateById(mallSerial);
  1042. } else {
  1043. MallOrderSerial mallSerial = new MallOrderSerial();
  1044. mallSerial.setSerialId(DistributedIdWorker.nextId());
  1045. mallSerial.setSerialCode(serialCode);
  1046. mallSerial.setSerialNo(1);
  1047. mallOrderSerialService.save(mallSerial);
  1048. }
  1049. String maxSerialNo = "";
  1050. if (1 == serialNo.toString().length()) {
  1051. maxSerialNo = "00000" + serialNo;
  1052. } else if (2 == serialNo.toString().length()) {
  1053. maxSerialNo = "0000" + serialNo;
  1054. } else if (3 == serialNo.toString().length()) {
  1055. maxSerialNo = "000" + serialNo;
  1056. } else if (4 == serialNo.toString().length()) {
  1057. maxSerialNo = "00" + serialNo;
  1058. } else if (5 == serialNo.toString().length()) {
  1059. maxSerialNo = "0" + serialNo;
  1060. } else if (6 == serialNo.toString().length()) {
  1061. maxSerialNo = serialNo.toString();
  1062. }
  1063. return nowDateIntString.substring(0, 8) + maxSerialNo + createBookingCode();
  1064. }
  1065. /**
  1066. * 取消订单
  1067. */
  1068. @ApiOperation(value = "取消订单", response = Rest.class)
  1069. @PostMapping("/cancelOrder")
  1070. @Transactional
  1071. public Rest cancelOrder(@RequestBody String body, @LoginUser Long userId) {
  1072. if (userId == null) {
  1073. return Rest.failure(-1, "账号未授权");
  1074. }
  1075. JSONObject json = JSONObject.parseObject(body);
  1076. String orderId = json.getString("orderId");
  1077. if ("".equals(orderId)) {
  1078. return Rest.failure("操作失败");
  1079. }
  1080. MallOrder order = new MallOrder();
  1081. order.setOrderId(Long.valueOf(orderId));
  1082. order.setOrderStatus(0);
  1083. if (mallOrderService.updateById(order)) {
  1084. List<MallOrderDetail> orderDetail = mallOrderDetailService.list(new QueryWrapper<MallOrderDetail>().eq("order_id", orderId));
  1085. if (!StringUtils.isEmpty(orderDetail)) {
  1086. Map<Long, Integer> orderSkudetailMap = orderDetail.stream().collect(Collectors.toMap(MallOrderDetail::getSkuDetailId, MallOrderDetail::getNumber));
  1087. List<MallGoodsSkudetail> skuDetail = mallGoodsSkudetailService.list(new QueryWrapper<MallGoodsSkudetail>().in("skudetail_id", orderSkudetailMap.keySet()));
  1088. for (MallGoodsSkudetail mallGoodsSkudetail : skuDetail) {
  1089. Long skuDetailId = mallGoodsSkudetail.getSkudetailId();
  1090. Integer orderSkuNumber = orderSkudetailMap.get(skuDetailId);
  1091. // 归还库存
  1092. if(mallGoodsSkudetailService.addStock(skuDetailId, orderSkuNumber) == 0) {
  1093. throw new RuntimeException("商品货品库存增加失败");
  1094. }
  1095. }
  1096. List<MallCouponUser> mallCouponUserList = mallCouponUserService.list(new QueryWrapper<MallCouponUser>().eq("user_id", userId).eq("order_id", orderId));
  1097. if(mallCouponUserList.size() > 0) {
  1098. //归还优惠券
  1099. for (MallCouponUser mallCouponUser : mallCouponUserList) {
  1100. mallCouponUser.setOrderId(null);
  1101. mallCouponUser.setUsedTime(null);
  1102. mallCouponUser.setStatus(0);
  1103. }
  1104. mallCouponUserService.updateBatchById(mallCouponUserList);
  1105. }
  1106. }
  1107. return Rest.ok();
  1108. } else {
  1109. return Rest.failure("操作失败");
  1110. }
  1111. }
  1112. /**
  1113. * 确认收货
  1114. */
  1115. @ApiOperation(value = "确认收货", response = Rest.class)
  1116. @PostMapping("/receipt")
  1117. public Rest receipt(@RequestBody String body, @LoginUser Long userId) {
  1118. if (userId == null) {
  1119. return Rest.failure(-1, "账号未授权");
  1120. }
  1121. JSONObject json = JSONObject.parseObject(body);
  1122. String orderId = json.getString("orderId");
  1123. if ("".equals(orderId)) {
  1124. return Rest.failure("操作失败");
  1125. }
  1126. MallOrder order = new MallOrder();
  1127. order.setOrderId(Long.valueOf(orderId));
  1128. order.setOrderStatus(2);
  1129. order.setShipStatus(2);
  1130. order.setConfirmTime(new Date());
  1131. if (mallOrderService.updateById(order)) {
  1132. return Rest.ok("收货成功");
  1133. } else {
  1134. return Rest.failure("操作失败");
  1135. }
  1136. }
  1137. private String createBookingCode() {
  1138. Random random = new Random();
  1139. int num = random.nextInt(10000);
  1140. String code = String.format("%04d", num);
  1141. return code;
  1142. }
  1143. /**
  1144. * 付款(后来新增)
  1145. */
  1146. @ApiOperation(value = "付款", response = Rest.class)
  1147. @PostMapping("/pay")
  1148. public Rest pay(@RequestBody String body) {
  1149. JSONObject json = JSONObject.parseObject(body);
  1150. String orderId = json.getString("order_id");
  1151. if ("".equals(orderId)) {
  1152. return Rest.failure("操作失败");
  1153. }
  1154. MallOrder order = mallOrderService.getById(orderId);
  1155. order.setPayStatus(1);
  1156. order.setShipStatus(0);
  1157. order.setPayId(UUIDUtil.uuid());
  1158. order.setPayTime(new Date());
  1159. if (mallOrderService.updateById(order)) {
  1160. return Rest.ok("支付成功");
  1161. } else {
  1162. return Rest.failure("操作失败");
  1163. }
  1164. }
  1165. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/555455
推荐阅读
相关标签
  

闽ICP备14008679号