orderDetail.js 8.9 KB

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