orderDetail.js 9.8 KB

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