order.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 = [], type = '0', group, inviter } = body;
  35. if (coupon.length > 1) throw new BusinessError(ErrorCode.DATA_INVALID, '目前只允许使用1张优惠券');
  36. // 检测商品是否可以下单
  37. for (const i of goods) {
  38. const { shop } = i;
  39. for (const g of i.goods) {
  40. const { goods_id: goods, goodsSpec_id: goodsSpec, num } = g;
  41. const { result, msg } = await this.ctx.service.util.trade.checkCanBuy({ shop, goods, goodsSpec, num }, false);
  42. if (!result) throw new BusinessError(ErrorCode.DATA_INVALID, msg);
  43. }
  44. }
  45. const orderData = {};
  46. const goodsSpecs = [];
  47. // 数据做快照处理
  48. // 1.地址快照
  49. const addressData = await this.addressModel.findById(address._id);
  50. if (!addressData) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到邮寄地址数据');
  51. // 2.商品快照
  52. const goodsData = [];
  53. // 商店不做快照,但是商品和商品对应的规格做快照
  54. const { populate } = this.ctx.service.shop.goodsSpec.getRefMods();
  55. for (const i of goods) {
  56. const { goods: goodsList, ...others } = i;
  57. const qp = [];
  58. for (const g of goodsList) {
  59. const { goodsSpec_id, num, cart_id } = g;
  60. let goodsSpec = await this.goodsSpecModel.findById(goodsSpec_id).populate(populate);
  61. if (!goodsSpec) continue;
  62. goodsSpec = JSON.parse(JSON.stringify(goodsSpec));
  63. // 将商店内容剔除
  64. const { goods: gd, ...dOthers } = goodsSpec;
  65. const gdOthers = _.omit(gd, [ 'shop' ]);
  66. const obj = { ...dOthers, goods: gdOthers, buy_num: num, tags: _.get(gdOthers, 'tags') };
  67. if (cart_id) obj.cart_id = cart_id;
  68. qp.push(obj);
  69. goodsSpecs.push({ id: goodsSpec_id, buy_num: num, sell_money: obj.sell_money, group_sell_money: _.get(obj, 'group_config.money'), type });
  70. }
  71. goodsData.push({ ...others, goods: qp });
  72. }
  73. // 3.商品总计明细.
  74. // 计算优惠券的明细
  75. const discountDetail = await this.ctx.service.user.userCoupon.computedOrderCouponDiscount(coupon, goodsSpecs);
  76. const totalDetailData = { ...total_detail, discount_detail: JSON.parse(JSON.stringify(discountDetail)) };
  77. // 接下来组织订单数据
  78. orderData.address = addressData;
  79. orderData.goods = goodsData;
  80. orderData.total_detail = totalDetailData;
  81. // 1.用户数据
  82. orderData.customer = customer;
  83. // 2.下单时间
  84. orderData.buy_time = moment().format('YYYY-MM-DD HH:mm:ss');
  85. // 3.订单号
  86. const str = this.ctx.service.util.trade.createNonceStr();
  87. orderData.no = `${moment().format('YYYYMMDDHHmmss')}-${str}`;
  88. // 4.状态
  89. orderData.status = '0';
  90. // #region 是否是团购
  91. orderData.type = type;
  92. if (type === '1' || group) {
  93. orderData.group = group;
  94. }
  95. // #endregion
  96. // 5.返现部分:邀请人: 自己发链接自己买不行
  97. if (customer !== inviter) orderData.inviter = inviter;
  98. // 生成数据
  99. const order_id = this.tran.insert('Order', orderData);
  100. // 处理库存,删除购物车
  101. await this.dealGoodsNum(goodsData);
  102. // 处理优惠券,改为使用过
  103. if (coupon.length > 1) await this.ctx.service.user.userCoupon.useCoupon(coupon, this.tran);
  104. await this.tran.run();
  105. // 创建定时任务(mq死信机制任务)
  106. await this.toMakeTask(order_id);
  107. return order_id;
  108. } catch (error) {
  109. await this.tran.rollback();
  110. console.error(error);
  111. throw new BusinessError(ErrorCode.SERVICE_FAULT, '订单发生错误,下单失败');
  112. } finally {
  113. // 清空事务
  114. this.tran.clean();
  115. }
  116. }
  117. /**
  118. * 取消订单(支付前)
  119. * @param {Object} body 参数体
  120. * @param {String} body.order_id 订单id
  121. */
  122. async cancel({ order_id }) {
  123. try {
  124. assert(order_id, '缺少订单信息');
  125. const order = await this.model.findById(order_id);
  126. if (!order) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  127. if (_.get(order, 'pay.result')) {
  128. throw new BusinessError(ErrorCode.DATA_INVALID, '该订单已支付完成,无法使用此接口');
  129. }
  130. // 退单分为 2 部分, 涉及价格不需要管.因为这是交钱之前的的操作,不涉及退款
  131. // 1.货物的库存
  132. const { goods: shopGoods, total_detail } = order;
  133. // 需要归还库存的商品规格列表:{_id:商品规格id,buy_num:购买的数量}
  134. for (const sg of shopGoods) {
  135. const { goods: goodsList } = sg;
  136. const list = goodsList.map(i => _.pick(i, [ '_id', 'buy_num' ]));
  137. for (const i of list) {
  138. const goodsSpec = await this.goodsSpecModel.findById(i._id, { num: 1 });
  139. if (!goodsSpec) continue;
  140. const newNum = this.ctx.plus(goodsSpec.num, i.buy_num);
  141. this.tran.update('GoodsSpec', i._id, { num: newNum });
  142. }
  143. }
  144. // 2.优惠券
  145. const { discount_detail } = total_detail;
  146. if (discount_detail) {
  147. // 第一层key值全都是使用的优惠券id.拿去改了就好了
  148. const couponIds = Object.keys(discount_detail);
  149. for (const uc_id of couponIds) {
  150. this.tran.update('UserCoupon', uc_id, { status: '0' });
  151. }
  152. }
  153. // 3.订单修改为关闭
  154. this.tran.update('Order', order_id, { status: '-1' });
  155. await this.tran.run();
  156. } catch (error) {
  157. await this.tran.rollback();
  158. console.error(error);
  159. throw new BusinessError(ErrorCode.SERVICE_FAULT, '订单取消失败');
  160. } finally {
  161. this.tran.clean();
  162. }
  163. }
  164. /**
  165. * 减库存,删除购物车
  166. * @param {Array} list 商品
  167. */
  168. async dealGoodsNum(list) {
  169. for (const i of list) {
  170. for (const g of i.goods) {
  171. const { _id, buy_num, cart_id } = g;
  172. const goodsSpec = await this.goodsSpecModel.findById(_id);
  173. const newNum = this.ctx.minus(goodsSpec.num, buy_num);
  174. this.tran.update('GoodsSpec', _id, { num: newNum });
  175. if (cart_id) this.tran.remove('Cart', cart_id);
  176. }
  177. }
  178. }
  179. /**
  180. * 进入下单页面
  181. * @param {Object} body 请求参数
  182. * @param body.key 缓存key
  183. */
  184. async toMakeOrder({ key }) {
  185. key = `${this.redisKey.orderKeyPrefix}${key}`;
  186. let data = await this.redis.get(key);
  187. if (!data) throw new BusinessError(ErrorCode.SERVICE_FAULT, '请求超时,请重新进入下单页');
  188. data = JSON.parse(data);
  189. let specsData = [];
  190. if (_.isArray(data)) {
  191. // 购物车来的: 1.循环校验 规格商品; 2.按店铺分组
  192. const { populate } = this.ctx.service.trade.cart.getRefMods();
  193. const carts = await this.cartModel.find({ _id: data }).populate(populate);
  194. for (const cart of carts) {
  195. const { result, msg } = await this.ctx.service.util.trade.checkCanBuy(cart, false);
  196. if (!result) throw new BusinessError(ErrorCode.DATA_INVALID, msg);
  197. }
  198. specsData = this.setCartsGoodsToPageData(carts);
  199. } else if (_.isObject(data)) {
  200. // 商品页单独买: 1.校验规格商品; 2:按店铺分组
  201. const { result, msg } = await this.ctx.service.util.trade.checkCanBuy(data, false);
  202. if (!result) throw new BusinessError(ErrorCode.DATA_INVALID, msg);
  203. const { populate } = this.ctx.service.shop.goodsSpec.getRefMods();
  204. const list = await this.goodsSpecModel.find({ _id: data.goodsSpec }).populate(populate);
  205. specsData = this.setGoodsToPageData(list, data.num);
  206. } else throw new BusinessError(ErrorCode.DATA_INVALID, '数据不正确,请重新下单');
  207. // 组装页面的数据
  208. const user = this.ctx.user;
  209. const customer = _.get(user, '_id');
  210. if (!customer) throw new BusinessError(ErrorCode.NOT_LOGIN, '未找到用户信息');
  211. const pageData = {};
  212. // 找到默认地址
  213. const address = await this.addressModel.findOne({ customer, is_default: '1' });
  214. pageData.address = address;
  215. // #region 团购部分
  216. const { type, group } = data;
  217. pageData.type = type; // 新添字段,订单类型
  218. pageData.group = group; // 新添字段,团购的团id
  219. // #endregion
  220. // 商品总价,各店铺的价格明细
  221. specsData = this.ctx.service.util.order.makeOrder_computedShopTotal(specsData, type);
  222. const shopTotalDetail = this.ctx.service.util.order.makerOrder_computedOrderTotal(specsData);
  223. pageData.goodsData = specsData;
  224. pageData.orderTotal = shopTotalDetail;
  225. // 优惠券列表
  226. // 查询优惠券列表
  227. const couponList = await this.ctx.service.user.userCoupon.toMakeOrder_getList(specsData);
  228. pageData.couponList = couponList;
  229. // 返现部分:添加推荐人信息
  230. pageData.inviter = _.get(data, 'inviter');
  231. return pageData;
  232. }
  233. /**
  234. * 单商品整理数据,剩下的可以简略
  235. * @param {Array} list 规格数组
  236. * @param num 购买数量
  237. */
  238. setGoodsToPageData(list, num) {
  239. // 按店铺分组,精简字段
  240. const arr = [];
  241. for (const i of list) {
  242. const obj = {};
  243. obj.shop_name = _.get(i.goods, 'shop.name');
  244. obj.shop = _.get(i.goods, 'shop._id');
  245. const goods = {};
  246. goods.goods_id = _.get(i.goods, '_id');
  247. goods.goods_name = _.get(i.goods, 'name');
  248. goods.goodsSpec_id = _.get(i, '_id');
  249. goods.goodsSpec_name = _.get(i, 'name');
  250. goods.freight = _.get(i, 'freight');
  251. goods.money = _.get(i, 'sell_money');
  252. goods.num = num;
  253. goods.file = _.get(i.goods, 'file');
  254. goods.tags = _.get(i.goods, 'tags');
  255. // #region 团购部分
  256. // 团购价
  257. goods.group_sell_money = _.get(i, 'group_config.money');
  258. // #endregion
  259. obj.goods = [ goods ];
  260. arr.push(obj);
  261. }
  262. return arr;
  263. }
  264. /**
  265. *购物车数据整理
  266. * @param {Array} list 规格数组
  267. */
  268. setCartsGoodsToPageData(list) {
  269. const arr = [];
  270. list = _.groupBy(list, 'shop._id');
  271. for (const key in list) {
  272. const data = list[key];
  273. const shopData = _.get(_.head(data), 'shop');
  274. const obj = {};
  275. obj.shop = _.get(shopData, '_id');
  276. obj.shop_name = _.get(shopData, 'name');
  277. const goodsList = [];
  278. for (const i of data) {
  279. const goods = {};
  280. goods.cart_id = _.get(i, '_id');
  281. goods.goods_id = _.get(i.goods, '_id');
  282. goods.goods_name = _.get(i.goods, 'name');
  283. goods.goodsSpec_id = _.get(i.goodsSpec, '_id');
  284. goods.goodsSpec_name = _.get(i.goodsSpec, 'name');
  285. goods.freight = _.get(i.goodsSpec, 'freight');
  286. goods.money = _.get(i.goodsSpec, 'sell_money');
  287. goods.num = _.get(i, 'num');
  288. goods.file = _.get(i.goods, 'file', []);
  289. goods.tags = _.get(i.goods, 'tags');
  290. // #region 团购部分
  291. // 团购价
  292. goods.group_sell_money = _.get(i.goodsSpec, 'group_config.money');
  293. // #endregion
  294. goodsList.push(goods);
  295. }
  296. obj.goods = goodsList;
  297. arr.push(obj);
  298. }
  299. return arr;
  300. }
  301. async afterQuery(filter, data) {
  302. data = JSON.parse(JSON.stringify(data));
  303. for (const i of data) {
  304. const { goods } = i;
  305. const buy_num_total = goods.reduce(
  306. (p, n) =>
  307. this.ctx.plus(
  308. p,
  309. n.goods.reduce((np, ng) => this.ctx.plus(np, ng.buy_num), 0)
  310. ),
  311. 0
  312. );
  313. i.buy_num_total = buy_num_total;
  314. i.real_pay = _.get(i, 'pay.pay_money');
  315. }
  316. return data;
  317. }
  318. async toMakeTask(order_id) {
  319. const { taskMqConfig } = this.app.config;
  320. const data = { service: 'trade.order', method: 'cancel', params: { order_id } };
  321. const config = await this.ctx.service.system.config.query();
  322. const setting = _.get(config, 'config.autoCloseOrder', -1);
  323. // 设置为小于等于0时,不进行自动关闭
  324. if (setting <= 0) return;
  325. await this.ctx.service.util.rabbitMq.makeTask(taskMqConfig.queue, data, 15);
  326. }
  327. }
  328. module.exports = OrderService;