orderDetail.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 { ObjectId } = require('mongoose').Types;
  7. const Transaction = require('mongoose-transactions');
  8. //
  9. class OrderDetailService extends CrudService {
  10. constructor(ctx) {
  11. super(ctx, 'orderdetail');
  12. this.model = this.ctx.model.Trade.OrderDetail;
  13. this.orderModel = this.ctx.model.Trade.Order;
  14. this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec;
  15. this.userCouponModel = this.ctx.model.User.UserCoupon;
  16. this.goodsRateModel = this.ctx.model.Shop.GoodsRate;
  17. this.afterSaleModel = this.ctx.model.Trade.AfterSale;
  18. this.tran = new Transaction();
  19. }
  20. async searchOrderTransport({ id, goods_id }) {
  21. const orderDetail = await this.model.findById(id);
  22. if (!id) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到订单信息');
  23. const { transport = [] } = orderDetail;
  24. let toSearch = [];
  25. if (goods_id) {
  26. // 传来指定商品,查有该商品的订单,但是如果没有,就查每一项中是否有 shop_transport_no 和 shop_transport_type
  27. // 如果有这俩属性,说明也有单子,也查出来
  28. toSearch = transport.filter(f => _.isArray(f.goods) && f.goods.find(fg => fg.goods_id === goods_id));
  29. console.log(toSearch);
  30. if (toSearch.length <= 0) {
  31. toSearch = transport.filter(f => f.shop_transport_no && f.shop_transport_type);
  32. }
  33. } else {
  34. toSearch = transport;
  35. }
  36. const result = [];
  37. for (const t of toSearch) {
  38. const { shop_transport_no: no, shop_transport_type: type } = t;
  39. if (!no || !type) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '缺少快递信息');
  40. const res = await this.ctx.service.util.kd100.search({ no, type });
  41. result.push(res);
  42. }
  43. return result;
  44. }
  45. /**
  46. * 创建:用户支付完成后的订单
  47. * @param {Object} body 请求参数体
  48. * @param body.order_id 下单的id
  49. * @param {Transaction} tran 数据库事务实例
  50. */
  51. async create({ order_id }, tran) {
  52. assert(order_id, '缺少支付订单信息');
  53. const order = await this.orderModel.findById(order_id);
  54. if (!order) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到支付订单的数据');
  55. // 返现部分
  56. const { customer, address, goods: shopGoods, no, status, buy_time, pay, total_detail: otd, inviter } = order;
  57. if (status === '0') throw new BusinessError(ErrorCode.DATA_INVALID, '订单未支付');
  58. const orderDetailData = { customer, address, order: order_id, buy_time, pay_time: _.get(pay, 'pay_time'), status, inviter };
  59. const shopMoneyDetail = this.ctx.service.util.order.shopMoneyDetail(order);
  60. // 分订单计数器
  61. let noTimes = 1;
  62. for (const s of shopGoods) {
  63. const shop = _.get(s, 'shop');
  64. const remarks = _.get(s, 'remarks');
  65. const goodsList = _.get(s, 'goods', []);
  66. const detailNo = `${no}-${noTimes}`;
  67. const total_detail = shopMoneyDetail[shop];
  68. // 优惠部分分割
  69. if (_.get(otd, 'discount_detail')) {
  70. // 如果有优惠部分,那就得找,优惠里面有没有对应的商品规格
  71. const discount_detail = this.getGoodsListDiscountDetail(goodsList, _.get(otd, 'discount_detail'));
  72. total_detail.discount_detail = discount_detail;
  73. }
  74. noTimes++;
  75. const obj = { ...orderDetailData, shop, goods: goodsList, no: detailNo, total_detail, remarks };
  76. // #region 团购
  77. const type = _.get(order, 'type');
  78. let group = _.get(order, 'group');
  79. if (type === '1') {
  80. // 说明是团购,需要找订单中有没有团的id
  81. obj.type = '1';
  82. obj.group = group;
  83. if (!group) {
  84. // 需要创建团,这是团长支付的单子,开团;然后把id回补
  85. group = await this.ctx.service.group.group.create(obj, tran);
  86. obj.group = group;
  87. tran.update('Order', order_id, { group, type: '1' });
  88. } else {
  89. // 需要参团操作,这是团员的单子,将人加入团中
  90. await this.ctx.service.group.group.join(customer, group, tran);
  91. }
  92. }
  93. // #endregion
  94. const orderDetail_id = tran.insert('OrderDetail', obj);
  95. // arr.push(obj);
  96. // 添加该商品是否和平台活动有关,做记录
  97. await this.ctx.service.trade.actOrder.create(orderDetail_id, obj, tran);
  98. }
  99. // await this.model.insertMany(arr);
  100. }
  101. /**
  102. * 将商品规格列表中,优惠的部分提取出来,分单用
  103. * @param {Array} goodsList 某店的商品列表
  104. * @param {Object} odd discount_detail 支付订单的优惠券设置
  105. */
  106. getGoodsListDiscountDetail(goodsList, odd) {
  107. const result = {};
  108. for (const uc_id in odd) {
  109. const detail = odd[uc_id];
  110. const obj = {};
  111. for (const g of goodsList) {
  112. const { _id } = g;
  113. const gdd = detail[_id];
  114. if (gdd) obj[_id] = gdd;
  115. }
  116. result[uc_id] = obj;
  117. }
  118. return result;
  119. }
  120. /**
  121. * 计算某店铺的金额总计
  122. * @param {Array} goodsList 商品规格列表
  123. */
  124. getTotalDetail(goodsList) {
  125. const goods_total = goodsList.reduce((p, n) => this.ctx.plus(p, this.ctx.multiply(n.sell_money, n.buy_num)), 0);
  126. const freight_total = goodsList.reduce((p, n) => this.ctx.plus(p, this.ctx.multiply(n.freight, n.buy_num)), 0);
  127. return { goods_total, freight_total };
  128. }
  129. async fetch(filter) {
  130. assert(filter);
  131. filter = await this.beforeFetch(filter);
  132. const { _id, id } = filter;
  133. if (_id || id) filter = { _id: ObjectId(_id || id) };
  134. const { populate } = this.getRefMods();
  135. let res = await this.model.findOne(filter).populate(populate).exec();
  136. res = JSON.parse(JSON.stringify(res));
  137. // 找售后和评论
  138. const afterSale = await this.afterSaleModel.find({ order_detail: res._id });
  139. const rate = await this.goodsRateModel.find({ orderDetail: res._id });
  140. const goods = _.get(res, 'goods', []);
  141. for (const g of goods) {
  142. const r = afterSale.find(f => ObjectId(_.get(f, 'goods._id')).equals(g._id));
  143. if (r) g.is_afterSale = true;
  144. else g.is_afterSale = false;
  145. const r2 = rate.find(f => ObjectId(_.get(f, 'goodsSpec')).equals(g._id));
  146. if (r2) {
  147. g.is_rate = true;
  148. g.rate = r2._id;
  149. } else g.is_rate = false;
  150. }
  151. res.goods = goods;
  152. return res;
  153. }
  154. async query(filter, { skip = 0, limit, sort, desc, projection } = {}) {
  155. // 处理排序
  156. if (sort && _.isString(sort)) {
  157. sort = { [sort]: desc ? -1 : 1 };
  158. } else if (sort && _.isArray(sort)) {
  159. sort = sort.map(f => ({ [f]: desc ? -1 : 1 })).reduce((p, c) => ({ ...p, ...c }), {});
  160. }
  161. let condition = _.cloneDeep(filter);
  162. condition = await this.beforeQuery(condition);
  163. condition = this.dealFilter(condition);
  164. // 过滤出ref字段
  165. const pipline = [{ $sort: { 'meta.createdAt': -1 } }];
  166. pipline.push({ $match: condition });
  167. // 整理字段
  168. // 店铺需要的字段
  169. pipline.push({ $addFields: { shop_id: { $toObjectId: '$shop' } } });
  170. pipline.push({
  171. $lookup: {
  172. from: 'shop',
  173. localField: 'shop_id',
  174. foreignField: '_id',
  175. as: 'shopInfo',
  176. },
  177. });
  178. pipline.push({ $addFields: { customer_id: { $toObjectId: '$customer' } } });
  179. pipline.push({
  180. $lookup: {
  181. from: 'user',
  182. localField: 'customer_id',
  183. foreignField: '_id',
  184. as: 'customerInfo',
  185. },
  186. });
  187. pipline.push({ $unwind: '$shopInfo' });
  188. pipline.push({ $unwind: '$customerInfo' });
  189. const lastProject = {
  190. $project: {
  191. _id: 1,
  192. type: 1,
  193. order: 1,
  194. buy_time: 1,
  195. pay_time: 1,
  196. status: 1,
  197. no: 1,
  198. group: 1,
  199. address: 1,
  200. goods: {
  201. _id: 1,
  202. sell_money: 1,
  203. freight: 1,
  204. name: 1,
  205. buy_num: 1,
  206. group_config: 1,
  207. goods: { name: 1, file: 1 },
  208. file: 1,
  209. },
  210. shop: {
  211. _id: '$shopInfo._id',
  212. name: '$shopInfo.name',
  213. },
  214. customer: {
  215. _id: '$customerInfo._id',
  216. name: '$customerInfo.name',
  217. },
  218. total_detail: 1,
  219. },
  220. };
  221. pipline.push(lastProject);
  222. const qPipline = _.cloneDeep(pipline);
  223. if (parseInt(skip) >= 0) qPipline.push({ $skip: parseInt(skip) });
  224. if (parseInt(limit)) qPipline.push({ $limit: parseInt(limit) });
  225. const rs = await this.model.aggregate(qPipline);
  226. const tPipline = _.cloneDeep(pipline);
  227. tPipline.push({ $addFields: { id: { $toString: '$_id' } } });
  228. tPipline.push({ $count: 'id' });
  229. const t = await this.model.aggregate(tPipline);
  230. const total = _.get(_.head(t), 'id');
  231. const list = [];
  232. for (const i of rs) {
  233. const { goods, _id: orderDetail } = i;
  234. const obj = _.cloneDeep(i);
  235. const real_pay = this.ctx.service.util.orderDetail.computedRealPay(obj);
  236. obj.real_pay = real_pay;
  237. obj.buy_num_total = goods.reduce((p, n) => this.ctx.plus(p, n.buy_num), 0);
  238. for (const og of obj.goods) {
  239. const { file = [], _id: goodsSpec } = og;
  240. const gfile = _.get(og, 'goods.file', []);
  241. const nf = [ ...file, ...gfile ];
  242. const url = _.get(_.head(nf), 'url');
  243. og.url = url;
  244. delete og.file;
  245. delete og.goods.file;
  246. // 评价
  247. const q = { orderDetail, goodsSpec };
  248. const rate = await this.goodsRateModel.findOne(q, { _id: 1 });
  249. obj.rate = _.get(rate, '_id');
  250. }
  251. // 售后
  252. const asum = await this.afterSaleModel.count({ order_detail: obj._id, status: { $nin: [ '0', '!1', '!2', '!3', '!4', '!5' ] } });
  253. obj.is_afterSale = asum > 0;
  254. list.push(obj);
  255. }
  256. return { data: list, total };
  257. }
  258. async update(filter, update, { projection } = {}) {
  259. assert(filter);
  260. assert(update);
  261. const { _id, id } = filter;
  262. if (_id || id) filter = { _id: ObjectId(_id || id) };
  263. const entity = await this.model.findOne(filter).exec();
  264. if (!entity) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
  265. try {
  266. this.tran.update('OrderDetail', filter._id, update);
  267. if (_.get(update, 'status') === '3') {
  268. // 积分部分
  269. await this.ctx.service.user.point.addPoints(filter._id, this.tran);
  270. // 返现部分
  271. await this.ctx.service.user.cashBack.create(filter._id, this.tran);
  272. }
  273. await this.tran.run();
  274. const e = await this.model.findOne(filter, projection).exec();
  275. return e;
  276. } catch (error) {
  277. await this.tran.rollback();
  278. } finally {
  279. this.tran.clean();
  280. }
  281. }
  282. }
  283. module.exports = OrderDetailService;