orderDetail.js 10 KB

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