order.js 19 KB

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