order.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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.platformActModel = this.ctx.model.System.PlatformAct;
  22. this.gjaModel = this.ctx.model.Shop.GoodsJoinAct;
  23. this.orderUtil = this.ctx.service.util.order;
  24. this.goodsConfigModel = this.ctx.model.Shop.GoodsConfig;
  25. this.tran = new Transaction();
  26. this.setModel = this.ctx.model.Shop.GoodsSet;
  27. }
  28. /**
  29. * 创建订单
  30. * 1.检测商品是否可以购买
  31. * 2.数据做快照处理
  32. * @param {Object} body
  33. */
  34. async create(body) {
  35. // 声明事务
  36. try {
  37. const user = this.ctx.user;
  38. const customer = _.get(user, '_id');
  39. if (!customer) throw new BusinessError(ErrorCode.NOT_LOGIN, '未找到用户信息');
  40. const { address, goods, coupon = [], plus_goods = [], inviter } = body;
  41. if (coupon.length > 1) throw new BusinessError(ErrorCode.DATA_INVALID, '目前只允许使用1张优惠券');
  42. // 检测商品是否可以下单
  43. const resetGoodsList = [];
  44. for (const i of goods) {
  45. const { shop, is_set = '1' } = i;
  46. if (is_set === '1') {
  47. // 非套装
  48. for (const g of i.goods) {
  49. const { goods_id: goods, goodsSpec_id: goodsSpec, num } = g;
  50. const { result, msg } = await this.ctx.service.util.trade.checkCanBuy({ shop, goods, goodsSpec, num }, false);
  51. if (!result) throw new BusinessError(ErrorCode.DATA_INVALID, msg);
  52. }
  53. resetGoodsList.push(i);
  54. } else {
  55. const { result, msg } = await this.ctx.service.util.trade.checkCanBuy(i, false);
  56. if (!result) throw new BusinessError(ErrorCode.DATA_INVALID, msg);
  57. }
  58. }
  59. const orderData = {};
  60. // 数据做快照处理
  61. // 1.地址快照
  62. const addressData = await this.addressModel.findById(address._id);
  63. if (!addressData) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到邮寄地址数据');
  64. // 2.商品快照
  65. const res = await this.orderUtil.makeOrderGoodsData(goods);
  66. // 活动和购物券计算数据不需要更改,而重组的商品列表需要进行数据的更改
  67. const { actList, goodsSpecs } = res;
  68. let { goodsData } = res;
  69. // 3.商品总计明细.
  70. // 加购不算在优惠内,所以先计算优惠券的明细
  71. const discountDetail = await this.ctx.service.user.userCoupon.computedOrderCouponDiscount(coupon, goodsSpecs);
  72. // 处理加购商品
  73. goodsData = await this.orderUtil.addPlusGoods(goodsData, plus_goods);
  74. // 计算价格
  75. goodsData = this.orderUtil.computedShopDetail(goodsData);
  76. const total_detail = {
  77. goods_total: goodsData.reduce((p, n) => this.ctx.plus(p, n.goods_total), 0),
  78. freight_total: goodsData.reduce((p, n) => this.ctx.plus(p, n.freight_total), 0),
  79. act: actList,
  80. };
  81. const totalDetailData = { ...total_detail, discount_detail: JSON.parse(JSON.stringify(discountDetail)) };
  82. // 接下来组织订单数据
  83. orderData.address = addressData;
  84. orderData.goods = goodsData;
  85. orderData.total_detail = totalDetailData;
  86. // 1.用户数据
  87. orderData.customer = customer;
  88. // 2.下单时间
  89. orderData.buy_time = moment().format('YYYY-MM-DD HH:mm:ss');
  90. // 3.订单号
  91. const str = this.ctx.service.util.trade.createNonceStr();
  92. orderData.no = `${moment().format('YYYYMMDDHHmmss')}-${str}`;
  93. // 4.状态
  94. orderData.status = '0';
  95. // 5.返现部分:邀请人: 自己发链接自己买不行
  96. if (customer !== inviter && ObjectId.isValid(inviter)) orderData.inviter = inviter;
  97. // 生成数据
  98. const order_id = this.tran.insert('Order', orderData);
  99. // 处理库存,删除购物车
  100. await this.dealGoodsNum(goodsData);
  101. // 处理优惠券,改为使用过
  102. if (coupon.length > 0) await this.ctx.service.user.userCoupon.useCoupon(coupon, this.tran);
  103. await this.tran.run();
  104. // 创建定时任务(mq死信机制任务)
  105. await this.toMakeTask(order_id);
  106. return order_id;
  107. } catch (error) {
  108. await this.tran.rollback();
  109. console.error(error);
  110. throw new BusinessError(ErrorCode.SERVICE_FAULT, '订单发生错误,下单失败');
  111. } finally {
  112. // 清空事务
  113. this.tran.clean();
  114. }
  115. }
  116. /**
  117. * 取消订单(支付前)
  118. * @param {Object} body 参数体
  119. * @param {String} body.order_id 订单id
  120. */
  121. async cancel({ order_id }) {
  122. try {
  123. assert(order_id, '缺少订单信息');
  124. const order = await this.model.findById(order_id);
  125. if (!order) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  126. if (_.get(order, 'pay.result')) {
  127. throw new BusinessError(ErrorCode.DATA_INVALID, '该订单已支付完成,无法使用此接口');
  128. }
  129. if (_.get(order, 'status') !== '0') {
  130. throw new BusinessError(ErrorCode.DATA_INVALID, '该订单不处于可以退单的状态');
  131. }
  132. // 退单分为 2 部分, 涉及价格不需要管.因为这是交钱之前的的操作,不涉及退款
  133. // 1.货物的库存
  134. const { goods: shopGoods, total_detail, is_set = '1' } = order;
  135. if (is_set === '1') {
  136. // 需要归还库存的商品规格列表:{_id:商品规格id,buy_num:购买的数量}
  137. for (const sg of shopGoods) {
  138. const { goods: goodsList } = sg;
  139. const list = goodsList.map(i => _.pick(i, [ '_id', 'buy_num' ]));
  140. for (const i of list) {
  141. const goodsSpec = await this.goodsSpecModel.findById(i._id, { num: 1 });
  142. if (!goodsSpec) continue;
  143. const newNum = this.ctx.plus(goodsSpec.num, i.buy_num);
  144. this.tran.update('GoodsSpec', i._id, { num: newNum });
  145. }
  146. }
  147. } else {
  148. // 套装退库存
  149. }
  150. // 2.优惠券
  151. const { discount_detail } = total_detail;
  152. if (discount_detail) {
  153. // 第一层key值全都是使用的优惠券id.拿去改了就好了
  154. const couponIds = Object.keys(discount_detail);
  155. for (const uc_id of couponIds) {
  156. this.tran.update('UserCoupon', uc_id, { status: '0' });
  157. }
  158. }
  159. // 3.订单修改为关闭
  160. this.tran.update('Order', order_id, { status: '-1' });
  161. await this.tran.run();
  162. } catch (error) {
  163. await this.tran.rollback();
  164. console.error(error);
  165. throw new BusinessError(ErrorCode.SERVICE_FAULT, '订单取消失败');
  166. } finally {
  167. this.tran.clean();
  168. }
  169. }
  170. /**
  171. * 减库存,删除购物车
  172. * @param {Array} list 商品
  173. */
  174. async dealGoodsNum(list) {
  175. for (const i of list) {
  176. const { is_set = '1' } = i;
  177. if (is_set === '1') {
  178. for (const g of i.goods) {
  179. const { _id, buy_num, cart_id } = g;
  180. const goodsSpec = await this.goodsSpecModel.findById(_id);
  181. const newNum = this.ctx.minus(goodsSpec.num, buy_num);
  182. this.tran.update('GoodsSpec', _id, { num: newNum });
  183. if (cart_id) {
  184. const num = await this.cartModel.count({ _id: cart_id });
  185. if (num > 0) {
  186. this.tran.remove('Cart', cart_id);
  187. }
  188. }
  189. // 活动相关:
  190. // 买赠:不一定非要处理赠品,赠品可能不在库中;
  191. // 特价,满减/折:没关系
  192. // 加价购,作为另一个商品出现,一样会减少库存,不需要处理
  193. // 先不处理活动库存问题.先有逻辑可以做到
  194. }
  195. } else {
  196. // 套装减库存
  197. const { goods, buy_num, cart_id } = i;
  198. for (const i of goods) {
  199. const { spec, set_num } = i;
  200. const specData = await this.goodsSpecModel.findById(spec._id, { num: 1 }).lean();
  201. const newNum = this.ctx.minus(specData.num, this.ctx.multiply(set_num, buy_num));
  202. this.tran.update('GoodsSpec', spec._id, { num: newNum });
  203. }
  204. if (cart_id) {
  205. const num = await this.cartModel.count({ _id: cart_id });
  206. if (num > 0) {
  207. this.tran.remove('Cart', cart_id);
  208. }
  209. }
  210. }
  211. }
  212. }
  213. /**
  214. * 进入下单页面
  215. * @param {Object} body 请求参数
  216. * @param body.key 缓存key
  217. * @property {Array} data key中的数据,可能是 [string],[object]; [string]:数据是购物车id; [object] :是直接购买的数据
  218. */
  219. async toMakeOrder({ key }) {
  220. key = `${this.redisKey.orderKeyPrefix}${key}`;
  221. let data = await this.redis.get(key);
  222. if (!data) throw new BusinessError(ErrorCode.SERVICE_FAULT, '请求超时,请重新进入下单页');
  223. data = JSON.parse(data);
  224. let specsData = [];
  225. // 根据缓存,整理商品数据
  226. if (!_.isArray(data)) throw new BusinessError(ErrorCode.DATA_INVALID, '数据不正确,请重新下单');
  227. const head = _.head(data);
  228. if (_.isString(head)) {
  229. // 购物车来的,将购物车中的数据拿出来转换下
  230. let carts = await this.cartModel.find({ _id: data });
  231. if (carts.length > 0) {
  232. carts = JSON.parse(JSON.stringify(carts));
  233. carts = carts.map(i => ({ ...i, cart_id: i._id }));
  234. }
  235. carts = await this.ctx.service.trade.cart.getCartGoodsAct(carts);
  236. data = carts;
  237. } else {
  238. data = await this.ctx.service.trade.cart.getCartGoodsAct(data);
  239. }
  240. const { result, msg } = await this.ctx.service.util.trade.checkCanBuy(data, false);
  241. if (!result) throw new BusinessError(ErrorCode.DATA_INVALID, msg);
  242. // 本次订单 有关活动的数据
  243. const actList = await this.getActList(data, true);
  244. // 正常整理商品的内容,与活动结合
  245. specsData = await this.getPageData(data, actList);
  246. // 组装页面的数据
  247. const user = this.ctx.user;
  248. const customer = _.get(user, '_id');
  249. if (!customer) throw new BusinessError(ErrorCode.NOT_LOGIN, '未找到用户信息');
  250. const pageData = {};
  251. // 商品总价,各店铺的价格明细
  252. specsData = this.ctx.service.util.order.makeOrder_computedShopTotal(specsData);
  253. const shopTotalDetail = this.ctx.service.util.order.makerOrder_computedOrderTotal(specsData);
  254. // 找到默认地址
  255. const address = await this.addressModel.findOne({ customer, is_default: '1' });
  256. pageData.address = address;
  257. // 优惠券列表
  258. // 查询优惠券列表
  259. const couponList = await this.ctx.service.user.userCoupon.toMakeOrder_getList(specsData);
  260. pageData.couponList = couponList;
  261. // 返现部分:添加推荐人信息
  262. const inviter = _.get(_.head(data), 'inviter');
  263. // const inviter = data.find((f) => ObjectId.isValid(f.inviter));
  264. if (inviter) pageData.inviter = inviter;
  265. // 活动部分
  266. // 将加价购拿出来,给前端,需要特殊处理;
  267. pageData.actList = actList.filter(f => f.platform_act_type === '4' && f.activity);
  268. // 满减/折 直接放在orderTotal中,作为明细,反正后面也不用; 只有discount为数字(金额)的情况,说明满足该满减/折的优惠,数组是不满足的
  269. const daList = actList.filter(f => (f.platform_act_type === '5' || f.platform_act_type === '6') && _.isNumber(f.discount));
  270. for (const da of daList) {
  271. const obj = { zh: da.title, key: da.platform_act, money: da.discount };
  272. shopTotalDetail.push(obj);
  273. }
  274. pageData.goodsData = specsData;
  275. pageData.orderTotal = shopTotalDetail;
  276. return pageData;
  277. }
  278. /**
  279. * 活动相关第一步: 处理规格和活动的问题
  280. * @param {Array} goodsList 商店商品列表
  281. * @param {Array} actList 活动列表
  282. */
  283. async dealAct(goodsList, actList) {
  284. // 套装没活动,直接略过
  285. if (actList.length <= 0) return;
  286. // 活动根据类型有优先级设置,需要按优先级进行处理
  287. // 特价(3)>满减(5)>满折(6)>加价购(4); 买赠(2)无所谓
  288. const spActs = actList.filter(f => f.platform_act_type === '3');
  289. this.orderUtil.dealAct_sp(goodsList, spActs);
  290. const dmActs = actList.filter(f => f.platform_act_type === '5');
  291. await this.orderUtil.dealAct_discount(goodsList, dmActs);
  292. const dpActs = actList.filter(f => f.platform_act_type === '6');
  293. await this.orderUtil.dealAct_discount(goodsList, dpActs);
  294. let plusActs = actList.filter(f => f.platform_act_type === '4');
  295. await this.orderUtil.dealAct_plus(goodsList, plusActs);
  296. plusActs = plusActs.filter(f => f.activity);
  297. const giftActs = actList.filter(f => f.platform_act_type === '2');
  298. await this.orderUtil.dealAct_gift(goodsList, giftActs);
  299. }
  300. /**
  301. * 处理该订单活动部分
  302. * * 该商品可能会参加多个活动,活动之间有叠加问题
  303. * * 买赠:没关系,只要去找赠品就行
  304. * * 特价:需要找到特价,将价格更改为特价
  305. * * 加价购: 满足下限金额时,组织数据,允许前端进行加价购
  306. * * 满减/折: 针对整个订单而言. 满足就处理,不满足就是不处理
  307. * * 套装:暂不处理
  308. * * ps1: 特价与满减/折叠加, 按特价计算总价再看满减/折; 加价购不在满减/折的金额下限计算范围内
  309. * * ps2: 满减与满折的优先级为:先满减,后满折(理论上不应该同时出现在一个商品上)
  310. * @param {Array} data 购物车数据(直接购买也会组织成购物车数据)
  311. * @param {Boolean} getAll 获取所有活动
  312. */
  313. async getActList(data) {
  314. const actList = [];
  315. for (const i of data) {
  316. const { act = [], goodsSpec: spec, is_set = '1' } = i;
  317. if (is_set !== '1') continue;
  318. if (act.length <= 0) continue;
  319. for (const a of act) {
  320. let platformAct = await this.platformActModel.findById(a);
  321. // 没有找到活动,略过
  322. if (!platformAct) continue;
  323. platformAct = JSON.parse(JSON.stringify(platformAct));
  324. // 活动未开启,略过
  325. if (_.get(platformAct, 'is_use') !== '0') continue;
  326. // 活动类型为 0&1不需要处理
  327. const type = _.get(platformAct, 'type');
  328. if (type === '1' || type === '0') continue;
  329. // 先找下是否处于活动设置的程序时间
  330. const start = _.get(platformAct, 'config.time_start');
  331. const end = _.get(platformAct, 'config.time_end');
  332. const r = moment().isBetween(start, end, null, '[]');
  333. // 不在程序设定的活动时间内,下一个
  334. if (!r) continue;
  335. // 有关最后活动总结数据问题:
  336. // 1.买赠:需要具体到规格
  337. // 2.特价:需要具体到规格
  338. // 3.加价购:需要和商品一起进行判断
  339. // 4&5:满减/折:需要和商品一起判断
  340. // 6.套装:先不考虑
  341. if (type === '2') {
  342. // 买赠,直接去到活动中找到赠品
  343. const gja = await this.gjaModel.findOne({ platform_act: platformAct._id, 'spec._id': spec }, { config: 1 });
  344. if (!gja) continue;
  345. const gift = _.get(gja, 'config.gift', []);
  346. actList.push({ platform_act: platformAct._id, platform_act_type: type, spec, gift });
  347. } else if (type === '3') {
  348. // 特价,找出特价
  349. const gja = await this.gjaModel.findOne({ platform_act: platformAct._id, 'spec._id': spec }, { config: 1 });
  350. if (!gja) continue;
  351. const sp_price = _.get(gja, 'config.sp_price');
  352. actList.push({ platform_act: platformAct._id, platform_act_type: type, spec, sp_price });
  353. } else if (type === '4') {
  354. // 加价购,找出加价购下限;如果判断下限够了,那就可以让前端去加价购
  355. const plus_money = _.get(platformAct, 'config.plus_money', 0);
  356. const obj = { platform_act: platformAct._id, platform_act_type: type, plus_money };
  357. const r = actList.find(f => _.isEqual(f, obj));
  358. if (!r) actList.push(obj);
  359. } else if (type === '5' || type === '6') {
  360. // 满减/折
  361. const discount = _.get(platformAct, 'config.discount', []);
  362. const obj = { platform_act: platformAct._id, platform_act_type: type, discount };
  363. const r = actList.find(f => _.isEqual(f, obj));
  364. if (!r) actList.push(obj);
  365. }
  366. }
  367. }
  368. return actList;
  369. }
  370. // 直接购买&购物车,这俩字段基本没差, 组织订单页商品数据
  371. async getPageData(data, actList) {
  372. const arr = [];
  373. for (const i of data) {
  374. const { goodsSpec, num, cart_id, is_set = '1', set_id, shop } = i;
  375. if (is_set === '1' || !set_id) {
  376. const d = await this.goodsSpecModel.aggregate([
  377. { $match: { _id: ObjectId(goodsSpec) } },
  378. // #region 处理店铺与商品部分
  379. { $addFields: { goods_id: { $toObjectId: '$goods' } } },
  380. {
  381. $lookup: {
  382. from: 'goods',
  383. localField: 'goods_id',
  384. foreignField: '_id',
  385. pipeline: [
  386. { $addFields: { shop_id: { $toObjectId: '$shop' } } },
  387. {
  388. $lookup: {
  389. from: 'shop',
  390. localField: 'shop_id',
  391. foreignField: '_id',
  392. pipeline: [{ $project: { name: 1 } }],
  393. as: 'shop',
  394. },
  395. },
  396. { $project: { name: 1, file: 1, tag: 1, act_tag: 1, shop: { $first: '$shop' } } },
  397. ],
  398. as: 'goods',
  399. },
  400. },
  401. { $unwind: '$goods' },
  402. // #endregion
  403. {
  404. $project: {
  405. _id: 0,
  406. shop: '$goods.shop._id',
  407. shop_name: '$goods.shop.name',
  408. goods_id: '$goods._id',
  409. goods_name: '$goods.name',
  410. goodsSpec_id: '$_id',
  411. goodsSpec_name: '$name',
  412. freight: { $toString: '$freight' },
  413. sell_money: { $toString: '$sell_money' },
  414. leader_price: { $toString: '$leader_price' },
  415. num: { $toDouble: num },
  416. file: '$goods.file',
  417. tags: '$goods.tags',
  418. act_tags: '$goods.act_tags',
  419. price: { $toDouble: '$sell_money' },
  420. },
  421. },
  422. ]);
  423. let gs = _.head(d);
  424. if (gs) gs = JSON.parse(JSON.stringify(gs));
  425. if (cart_id) gs.cart_id = cart_id;
  426. arr.push(gs);
  427. } else {
  428. // 套装信息
  429. const setData = await this.setModel.findById(set_id).lean();
  430. const { _id, set = [], sell_money, name, freight } = setData;
  431. const newSet = [];
  432. const obj = { _id, set_id: _id, name, sell_money, is_set: '0', num, cart_id, freight, shop };
  433. for (const s of set) {
  434. const { goods, goods_name, spec, spec_name, set_num } = s;
  435. const goodsData = await this.goodsModel.findById(goods, { file: 1 }).lean();
  436. const specData = await this.goodsSpecModel.findById(spec, { file: 1 }).lean();
  437. const file = [ ..._.get(specData, 'file', []), ..._.get(goodsData, 'file', []) ];
  438. const newSetData = { goods_name, goods_id: goods, spec_name, file, set_num };
  439. newSet.push(newSetData);
  440. }
  441. obj.goods = newSet;
  442. arr.push(obj);
  443. }
  444. }
  445. // 检测是否是团长,使用团长价格
  446. const user = _.get(this.ctx, 'user');
  447. if (!user) throw new BusinessError(ErrorCode.NOT_LOGIN);
  448. const is_leader = _.get(user, 'is_leader', '1');
  449. if (is_leader === '0') {
  450. for (const i of arr) {
  451. const { is_set = '1' } = i;
  452. // 套装不需要团长价格
  453. if (is_set !== '1') continue;
  454. if (i.leader_price) {
  455. i.leader_price = this.ctx.toNumber(i.leader_price);
  456. i.price = i.leader_price;
  457. }
  458. }
  459. }
  460. // 平铺数据后,需要处理活动相关部分
  461. // 经过处理后的数据,会添加act字段,表明与活动有关的信息
  462. await this.dealAct(arr, actList);
  463. const result = await this.toMakeGroupData(arr);
  464. return result;
  465. }
  466. /**
  467. * 将平铺的数据按店铺分组形成
  468. * * [ { shop:${value}, shop_name:${value}, goods:${value} } ]
  469. * 的形式
  470. * @param {Array} cartList 平铺的数据集合
  471. */
  472. async toMakeGroupData(cartList) {
  473. const notSetList = cartList.filter(f => _.get(f, 'is_set', '1') === '1');
  474. const setList = cartList.filter(f => _.get(f, 'is_set', '1') === '0');
  475. const list = Object.values(_.groupBy(notSetList, 'shop'));
  476. const result = [ ...setList ];
  477. // 按店铺分组
  478. for (const i of list) {
  479. const head = _.head(i);
  480. const obj = { shop: _.get(head, 'shop'), shop_name: _.get(head, 'shop_name') };
  481. const goods = i.map(e => _.omit(e, [ 'shop', 'shop_name' ]));
  482. obj.goods = goods;
  483. result.push(obj);
  484. }
  485. return result;
  486. }
  487. async afterQuery(filter, data) {
  488. data = JSON.parse(JSON.stringify(data));
  489. for (const i of data) {
  490. const { goods } = i;
  491. let buy_num_total = 0;
  492. for (const g of goods) {
  493. const { is_set = '1' } = g;
  494. if (is_set === '1') {
  495. const bn = g.goods.reduce((p, n) => this.ctx.plus(p, n.buy_num), 0);
  496. buy_num_total = this.ctx.plus(buy_num_total, bn);
  497. } else {
  498. buy_num_total = this.ctx.plus(buy_num_total, g.buy_num);
  499. }
  500. }
  501. i.buy_num_total = buy_num_total;
  502. i.real_pay = _.get(i, 'pay.pay_money');
  503. }
  504. return data;
  505. }
  506. async afterFetch(filter, data) {
  507. data = JSON.parse(JSON.stringify(data));
  508. const total_detail = _.get(data, 'total_detail', {});
  509. data.total_detail = await this.ctx.service.trade.orderDetail.fetchResetTotalDetail(total_detail);
  510. return data;
  511. }
  512. async toMakeTask(order_id) {
  513. const { taskMqConfig } = this.app.config;
  514. const data = { service: 'trade.order', method: 'cancel', params: { order_id } };
  515. const config = await this.ctx.service.system.config.query();
  516. const setting = _.get(config, 'config.autoCloseOrder', -1);
  517. // 设置为小于等于0时,不进行自动关闭
  518. if (setting <= 0) return;
  519. await this.ctx.service.util.rabbitMq.makeTask(taskMqConfig.queue, data, 15);
  520. }
  521. }
  522. module.exports = OrderService;