order.js 13 KB

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