order.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const moment = require('moment');
  7. const Transaction = require('mongoose-transactions');
  8. //
  9. class OrderService extends CrudService {
  10. constructor(ctx) {
  11. super(ctx, 'order');
  12. this.redis = this.app.redis;
  13. this.redisKey = this.app.config.redisKey;
  14. this.model = this.ctx.model.Trade.Order;
  15. this.goodsModel = this.ctx.model.Shop.Goods;
  16. this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec;
  17. this.addressModel = this.ctx.model.User.Address;
  18. this.cartModel = this.ctx.model.Trade.Cart;
  19. this.userCouponModel = this.ctx.model.User.UserCoupon;
  20. this.tran = new Transaction();
  21. }
  22. /**
  23. * 创建订单
  24. * 1.检测商品是否可以购买
  25. * 2.数据做快照处理
  26. * @param {Object} body
  27. */
  28. async create(body) {
  29. // 声明事务
  30. try {
  31. const user = this.ctx.user;
  32. const customer = _.get(user, '_id');
  33. if (!customer) throw new BusinessError(ErrorCode.NOT_LOGIN, '未找到用户信息');
  34. const { address, goods, total_detail, coupon = [] } = body;
  35. // 检测商品是否可以下单
  36. for (const i of goods) {
  37. const { shop } = i;
  38. for (const g of i.goods) {
  39. const { goods_id: goods, goodsSpec_id: goodsSpec, num } = g;
  40. const { result, msg } = await this.ctx.service.util.trade.checkCanBuy({ shop, goods, goodsSpec, num }, false);
  41. if (!result) throw new BusinessError(ErrorCode.DATA_INVALID, msg);
  42. }
  43. }
  44. const orderData = {};
  45. const goodsSpecs = [];
  46. // 数据做快照处理
  47. // 1.地址快照
  48. const addressData = await this.addressModel.findById(address._id);
  49. if (!addressData) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到邮寄地址数据');
  50. // 2.商品快照
  51. const goodsData = [];
  52. // 商店不做快照,但是商品和商品对应的规格做快照
  53. const { populate } = this.ctx.service.shop.goodsSpec.getRefMods();
  54. for (const i of goods) {
  55. const { goods: goodsList, ...others } = i;
  56. const qp = [];
  57. for (const g of goodsList) {
  58. const { goodsSpec_id, num, cart_id } = g;
  59. let d = await this.goodsSpecModel.findById(goodsSpec_id).populate(populate);
  60. if (!d) continue;
  61. d = JSON.parse(JSON.stringify(d));
  62. // 将商店内容剔除
  63. const { goods: gd, ...dOthers } = d;
  64. const gdOthers = _.omit(gd, [ 'shop' ]);
  65. const obj = { ...dOthers, goods: gdOthers, buy_num: num, tags: _.get(gdOthers, 'tags') };
  66. if (cart_id) obj.cart_id = cart_id;
  67. qp.push(obj);
  68. goodsSpecs.push({ id: goodsSpec_id, buy_num: num });
  69. }
  70. goodsData.push({ ...others, goods: qp });
  71. }
  72. // 3.商品总计明细.
  73. // 计算优惠券的明细
  74. const discountDetail = await this.ctx.service.user.userCoupon.computedOrderCouponDiscount(coupon, goodsSpecs);
  75. const totalDetailData = { ...total_detail, discount_detail: JSON.parse(JSON.stringify(discountDetail)) };
  76. // 接下来组织订单数据
  77. orderData.address = addressData;
  78. orderData.goods = goodsData;
  79. orderData.total_detail = totalDetailData;
  80. // 1.用户数据
  81. orderData.customer = customer;
  82. // 2.下单时间
  83. orderData.buy_time = moment().format('YYYY-MM-DD HH:mm:ss');
  84. // 3.订单号
  85. const str = this.ctx.service.util.trade.createNonceStr();
  86. orderData.no = `${moment().format('YYYYMMDDHHmmss')}-${str}`;
  87. // 4.状态
  88. orderData.status = '0';
  89. // 生成数据
  90. // const order = await this.model.create(orderData);
  91. const order_id = this.tran.insert('Order', orderData);
  92. // 处理库存,删除购物车
  93. await this.dealGoodsNum(goodsData);
  94. // 处理优惠券,改为使用过
  95. await this.ctx.service.user.userCoupon.useCoupon(coupon, this.tran);
  96. await this.tran.run();
  97. return order_id;
  98. } catch (error) {
  99. await this.tran.rollback();
  100. console.error(error);
  101. throw new BusinessError(ErrorCode.SERVICE_FAULT, '订单发生错误,下单失败');
  102. } finally {
  103. // 清空事务
  104. this.tran.clean();
  105. }
  106. }
  107. /**
  108. * 取消订单(支付前)
  109. * @param {Object} body 参数体
  110. * @param {String} body.order_id 订单id
  111. */
  112. async cancel({ order_id }) {
  113. try {
  114. const order = await this.model.findById(order_id);
  115. if (!order) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  116. // 退单分为 2 部分, 涉及价格不需要管.因为这是交钱之前的的操作,不涉及退款
  117. // 1.货物的库存
  118. const { goods: shopGoods, total_detail } = order;
  119. // 需要归还库存的商品规格列表:{_id:商品规格id,buy_num:购买的数量}
  120. for (const sg of shopGoods) {
  121. const { goods: goodsList } = sg;
  122. const list = goodsList.map(i => _.pick(i, [ '_id', 'buy_num' ]));
  123. for (const i of list) {
  124. const goodsSpec = await this.goodsSpecModel.findById(i._id, { num: 1 });
  125. if (!goodsSpec) continue;
  126. const newNum = this.ctx.plus(goodsSpec.num, i.buy_num);
  127. this.tran.update('GoodsSpec', i._id, { num: newNum });
  128. }
  129. }
  130. // 2.优惠券
  131. const { discount_detail } = total_detail;
  132. if (discount_detail) {
  133. // 第一层key值全都是使用的优惠券id.拿去改了就好了
  134. const couponIds = Object.keys(discount_detail);
  135. for (const uc_id of couponIds) {
  136. this.tran.update('UserCoupon', uc_id, { status: '0' });
  137. }
  138. }
  139. // 3.订单修改为关闭
  140. this.tran.update('Order', order_id, { status: '-1' });
  141. await this.tran.run();
  142. } catch (error) {
  143. await this.tran.rollback();
  144. console.error(error);
  145. throw new BusinessError(ErrorCode.SERVICE_FAULT, '订单取消失败');
  146. } finally {
  147. this.tran.clean();
  148. }
  149. }
  150. /**
  151. * 减库存,删除购物车
  152. * @param {Array} list 商品
  153. */
  154. async dealGoodsNum(list) {
  155. for (const i of list) {
  156. for (const g of i.goods) {
  157. const { _id, buy_num, cart_id } = g;
  158. const goodsSpec = await this.goodsSpecModel.findById(_id);
  159. const newNum = this.ctx.minus(goodsSpec.num, buy_num);
  160. this.tran.update('GoodsSpec', _id, { num: newNum });
  161. if (cart_id) this.tran.remove('Cart', cart_id);
  162. }
  163. }
  164. }
  165. /**
  166. * 进入下单页面
  167. * @param {Object} body 请求参数
  168. * @param body.key 缓存key
  169. */
  170. async toMakeOrder({ key }) {
  171. key = `${this.redisKey.orderKeyPrefix}${key}`;
  172. let data = await this.redis.get(key);
  173. if (!data) throw new BusinessError(ErrorCode.SERVICE_FAULT, '请求超时,请重新进入下单页');
  174. data = JSON.parse(data);
  175. let specsData = [];
  176. if (_.isArray(data)) {
  177. // 购物车来的: 1.循环校验 规格商品; 2.按店铺分组
  178. const { populate } = this.ctx.service.trade.cart.getRefMods();
  179. const carts = await this.cartModel.find({ _id: data }).populate(populate);
  180. for (const cart of carts) {
  181. const { result, msg } = await this.ctx.service.util.trade.checkCanBuy(cart, false);
  182. if (!result) throw new BusinessError(ErrorCode.DATA_INVALID, msg);
  183. }
  184. specsData = this.setCartsGoodsToPageData(carts);
  185. } else if (_.isObject(data)) {
  186. // 商品页单独买: 1.校验规格商品; 2:按店铺分组
  187. const { result, msg } = await this.ctx.service.util.trade.checkCanBuy(data, false);
  188. if (!result) throw new BusinessError(ErrorCode.DATA_INVALID, msg);
  189. const { populate } = this.ctx.service.shop.goodsSpec.getRefMods();
  190. const list = await this.goodsSpecModel.find({ _id: data.goodsSpec }).populate(populate);
  191. specsData = this.setGoodsToPageData(list, data.num);
  192. } else throw new BusinessError(ErrorCode.DATA_INVALID, '数据不正确,请重新下单');
  193. // 组装页面的数据
  194. const user = this.ctx.user;
  195. const customer = _.get(user, '_id');
  196. if (!customer) throw new BusinessError(ErrorCode.NOT_LOGIN, '未找到用户信息');
  197. const pageData = {};
  198. // 找到默认地址
  199. const address = await this.addressModel.findOne({ customer, is_default: '1' });
  200. pageData.address = address;
  201. // 商品总价,各店铺的价格明细
  202. specsData = this.computedShopTotal(specsData);
  203. const shopTotalDetail = this.computedAllTotal(specsData);
  204. pageData.goodsData = specsData;
  205. pageData.orderTotal = shopTotalDetail;
  206. // 优惠券列表
  207. const couponList = await this.ctx.service.user.userCoupon.toMakeOrder_getList(specsData);
  208. pageData.couponList = couponList;
  209. // 查询优惠券列表
  210. return pageData;
  211. }
  212. /**
  213. * 计算商店的结算
  214. * @param {Array} list 按店铺分组的商品列表
  215. */
  216. computedShopTotal(list) {
  217. for (const i of list) {
  218. i.goods_total = i.goods.reduce((p, n) => this.ctx.plus(p, this.ctx.multiply(n.money, n.num)), 0);
  219. i.freight_total = i.goods.reduce((p, n) => this.ctx.plus(p, this.ctx.multiply(n.freight, n.num)), 0);
  220. }
  221. return list;
  222. }
  223. /**
  224. * 计算订单的结算
  225. * @param {Array} list 按店铺分组的商品列表
  226. */
  227. computedAllTotal(list) {
  228. const obj = {
  229. goods_total: list.reduce((p, n) => this.ctx.plus(p, n.goods_total), 0),
  230. freight_total: list.reduce((p, n) => this.ctx.plus(p, n.freight_total), 0),
  231. };
  232. return obj;
  233. }
  234. /**
  235. * 单商品整理数据,剩下的可以简略
  236. * @param {Array} list 规格数组
  237. * @param num 购买数量
  238. */
  239. setGoodsToPageData(list, num) {
  240. // 按店铺分组,精简字段
  241. const arr = [];
  242. for (const i of list) {
  243. const obj = {};
  244. obj.shop_name = _.get(i.goods, 'shop.name');
  245. obj.shop = _.get(i.goods, 'shop._id');
  246. const goods = {};
  247. goods.goods_id = _.get(i.goods, '_id');
  248. goods.goods_name = _.get(i.goods, 'name');
  249. goods.goodsSpec_id = _.get(i, '_id');
  250. goods.goodsSpec_name = _.get(i, 'name');
  251. goods.freight = _.get(i, 'freight');
  252. goods.money = _.get(i, 'sell_money');
  253. goods.num = num;
  254. goods.file = _.get(i.goods, 'file');
  255. goods.tags = _.get(i.goods, 'tags');
  256. obj.goods = [ goods ];
  257. arr.push(obj);
  258. }
  259. return arr;
  260. }
  261. /**
  262. *购物车数据整理
  263. * @param {Array} list 规格数组
  264. */
  265. setCartsGoodsToPageData(list) {
  266. const arr = [];
  267. list = _.groupBy(list, 'shop._id');
  268. for (const key in list) {
  269. const data = list[key];
  270. const shopData = _.get(_.head(data), 'shop');
  271. const obj = {};
  272. obj.shop = _.get(shopData, '_id');
  273. obj.shop_name = _.get(shopData, 'name');
  274. const goodsList = [];
  275. for (const i of data) {
  276. const goods = {};
  277. goods.cart_id = _.get(i, '_id');
  278. goods.goods_id = _.get(i.goods, '_id');
  279. goods.goods_name = _.get(i.goods, 'name');
  280. goods.goodsSpec_id = _.get(i.goodsSpec, '_id');
  281. goods.goodsSpec_name = _.get(i.goodsSpec, 'name');
  282. goods.freight = _.get(i.goodsSpec, 'freight');
  283. goods.money = _.get(i.goodsSpec, 'sell_money');
  284. goods.num = _.get(i, 'num');
  285. goods.file = _.get(i.goods, 'file', []);
  286. goods.tags = _.get(i.goods, 'tags');
  287. goodsList.push(goods);
  288. }
  289. obj.goods = goodsList;
  290. arr.push(obj);
  291. }
  292. return arr;
  293. }
  294. }
  295. module.exports = OrderService;